5

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.

Not me
  • 139
  • 10
  • 2
    Easy, just enter `fix show` into ghci before running `main` to fix the way `show` works. ;-) (You will need to import `Data.Function`.) – Daniel Wagner Aug 11 '20 at 00:28
  • 6
    @DanielWagner Some advanced Haskellers may think this ia a cute joke, but it will just confuse anyone asking this question. – amalloy Aug 11 '20 at 01:11
  • @amalloy I have more faith in our learny bois than you do. A winky face, and ghci immediately answering with more backslashes than you can shake a stick at, will be enough clue for anybody that it's just for funsies. And if not, now we have two incredibly serious comments telling them, too! – Daniel Wagner Aug 11 '20 at 01:21

1 Answers1

11

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.

happydave
  • 7,127
  • 1
  • 26
  • 25
  • 2
    By the way, see https://stackoverflow.com/questions/968198/haskell-show-screwed-up/968228#968228 for an explanation of why the quotes are added – happydave Aug 11 '20 at 00:24