English 中文(简体)
Haskell解析器在where子句中发生错误。
原标题:
  • 时间:2009-01-05 11:14:23
  •  标签:

第一个where部分中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,但它的语法规则使我感到困惑。错误信息是: [请注意,这是拼音,汉字上的语法存在歧义] wǒ zhèngzài xuéxí Haskell, dàn tā de yǔfǎ guīzé shǐ wǒ gǎndào kùnhuò. Cùowù xìnxī shì:

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

pelindrome.hs:5:8: parse error on input `rs 
最佳回答

Your indentation was wrong and i think you can only have one where in there (i could be very well wrong. I m not a haskell guy). There was also a argument missing for the call to rev (an empty list):

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")

Prints out:

"helloolleh"

I m going to try to understand it now. Anyway, have fun!

Edit: Makes perfect sense to me now. I think that s the right version. For Haskell indentation rules, read Haskell Indentation

问题回答

@litb: You can rewrite con in way

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).





相关问题
热门标签