2009-01-05 71 views
4

rs定義中的第一個where部分有什麼問題?Haskell語法分析程序錯誤,在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' 

回答

12

你的縮進是錯誤的,我認爲你只能有一個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

+0

你說得對,rs必須從前一行的con開始。這是奇怪的規則。 – 2009-01-05 11:52:24

+0

不奇怪:同樣的語法層次 - >相同的縮進 – Svante 2009-01-05 12:04:25

0

@litb:您可以在其中是如何++中拉開序幕實現方式

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) 

改寫CON。我以前的版本是如何以尾調用方式(例如Erlang)以非惰性函數或邏輯語言編寫的。