Thursday, August 18, 2022

[FIXED] Why is this Haskell program making backslashes?

Issue

I'm new to Haskell, and wrote this program to practice functional programming. I have no idea if it is a good program, except for two things.

  • It works (it shows me the path from 6 to 1 in a Collatz tree)
  • It prints way too many backslashes
next_step :: Integer -> Integer
collatz :: Integer -> String

next_step n = do
        if (n `mod` 2) == 0 then
                n `div` 2
        else
                (n * 3) + 1

collatz 1 = "1"
collatz n = (show n) ++ " -> " ++ (show (collatz (next_step n)))

main = putStrLn (collatz 6)

Output:

6 -> "3 -> \"10 -> \\\"5 -> \\\\\\\"16 -> \\\\\\\\\\\\\\\"8 -> \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"4 -> \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"2 -> \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"1\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"\\\"\""

I would like for the backslashes to go away.


Solution

collatz already returns a string, so you don't need to call show on it:

collatz n = show(n) ++ " -> " ++ collatz (next_step n)

Using show adds quotes, which then causes the backslashes due to nested quotes.



Answered By - happydave
Answer Checked By - Robin (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.