where子句中的Haskell解析器错误

时间:2009-01-05 11:14:24

标签: syntax haskell

rs定义首先在哪个部分有什么问题?

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'

2 个答案:

答案 0 :(得分:13)

你的缩进是错误的,我认为你只能有一个where(我可能是错的。我不是一个哈克尔人)。对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

答案 1 :(得分: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)

这是在前奏中实现++的方式。我之前的版本是如何用尾部调用方式(例如Erlang)以非惰性函数或逻辑语言编写它。