我是Haskell的新手,并编写了此程序来练习函数式编程。除了两件事,我不知道这是否是一个好的程序。

  • 它起作用(它向我显示了Collat​​z树中从6到1的路径)
  • 打印太多反斜线

  • 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添加引号,然后由于嵌套引号而引起反斜杠。

    08-28 06:28