Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Haskell program making backslashes?

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.

like image 745
Not me Avatar asked Aug 10 '20 23:08

Not me


People also ask

Why isn't Haskell used in mainstream programming?

Another reason for the lack of Haskell, and other functional languages, in mainstream use is that programming languages are rarely thought of as tools (even though they are).

What are the benefits of Haskell?

Along with the benefits of functional programming, Haskell has its own benefits that promote security and stability and allows building fault-tolerant programs. Haskell’s advantages include: it, by default, uses lazy evaluation, which means things only get evaluated if they are needed. This can result in faster programs.

Is Haskell really the fastest programming language?

And this might be true. For most applications, though, the difference in speed is so small that it's utterly irrelevant. For instance, take a look at the Computer Language Benchmarks Game, where Haskell compares favorably to most of the so called "fast" languages.

What are the types of expressions in Haskell?

Every expression in Haskell has a type, including functions and if statements The compiler can usually infer the types of expressions, but you should generally write out the type signature for top level functions and expressions.


Video Answer


1 Answers

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.

like image 116
happydave Avatar answered Nov 15 '22 08:11

happydave