我是Haskell的新手,并编写了此程序来练习函数式编程。除了两件事,我不知道这是否是一个好的程序。
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)
输出:6 -> "3 -> \"10 -> \\\"5 -> \\\\\\\"16 -> \\\\\\\\\\\\\\\"8 -> \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"4 -> \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"2 -> \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"1\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"\\\"\""
我希望反斜杠消失。 最佳答案
collatz
已经返回一个字符串,因此您无需在其上调用show
:
collatz n = show(n) ++ " -> " ++ collatz (next_step n)
使用show
添加引号,然后由于嵌套引号而引起反斜杠。