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.
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.
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With