6

rs第一个 where 部分的定义有什么问题?

palindrome :: [a] -> [a]

palindrome xs = con xs rs
    where con a b = rev (rev a []) b
        rs = rev xs                        -- here
        where rev [] rs = rs
            rev (x:xs) rs = rev xs (x:rs)

我只是在学习 Haskell,但它的语法规则让我感到困惑。错误信息是

[1 of 1] Compiling Main             ( pelindrome.hs, interpreted )

pelindrome.hs:5:8: parse error on input `rs'
4

2 回答 2

14

你的缩进是错误的,我认为你只能有一个where(我可能错了。我不是一个haskell人)。调用rev(空列表)还缺少一个参数:

palindrome :: [a] -> [a]
palindrome xs = con xs rs
    where con a b = rev (rev a []) b
          rs = rev xs []                       -- here
          rev [] rs = rs
          rev (x:xs) rs = rev xs (x:rs)

main = print (palindrome "hello")

打印出来:

"helloolleh"

我现在要试着理解它。不管怎样,玩得开心!

编辑:现在对我来说很有意义。我认为这是正确的版本。有关 Haskell 缩进规则,请阅读Haskell Indentation

于 2009-01-05T11:27:38.087 回答
0

@litb:您可以以方式重写 con

palindrome :: [a] -> [a]
palindrome xs = con xs rs
    where con [] b = b
          con (x:xs) b = x:con xs b
          rs = rev xs []                       -- here
          rev [] rs = rs
          rev (x:xs) rs = rev xs (x:rs)

which is how ++ is implemented in prelude. My previous version is way how to write it in non lazy functional or logical languages in tail call fashion (e.g. Erlang).

于 2009-01-06T18:17:15.357 回答