解析错误(=),对于列表使用模式匹配的函数?

时间:2015-10-27 19:20:34

标签: haskell pattern-matching

list (x:xs) = "this letter is " ++ [x] ++ " and " ++ function xs
    where  function [] = "Empty"
           function x:[] = "Singlet"
           function x:y:[] = "Double"
           function x:y:xs = "LARGE list!"

知道为什么这个功能不起作用我得到

  

解析输入'='

时的错误

2 个答案:

答案 0 :(得分:8)

我得到的错误消息有点不同,但至少有一个错误的代码是它缺少围绕各种列表模式的括号:

list (x:xs) = "this letter is " ++ [x] ++ " and " ++ function xs
    where function [] = "Empty"
          function (x:[]) = "Singlet"
          function (x:y:[]) = "Double"
          function (x:y:xs) = "LARGE list!"

编译并运作:

> list "foo"
"this letter is f and Double"
> list "barbaz"
"this letter is b and LARGE list!"
但是,它不完整,因为它不匹配空列表。

更完整,也许更惯用的版本将是这样的:

list :: String -> String
list [] = "the list is empty"
list (x:xs) = "this letter is " ++ [x] ++ " and " ++ function xs
    where function [] = "Empty"
          function [_] = "Singlet"
          function [_,_] = "Double"
          function (_:_:_) = "LARGE list!"

答案 1 :(得分:6)

您看到的错误是因为您的代码包含制表符。您的编辑器设置为将选项卡显示为四个空格,这使其缩进看起来正确,而Haskell将它们计为8,给出

list (x:xs) = "this letter is " ++ [x] ++ " and " ++ function xs
    where  function [] = "Empty"
               function x:[] = "Singlet"
               function x:y:[] = "Double"
                   function x:y:xs = "LARGE list!"

此错误特别隐蔽,因为stackoverflow markdown 将制表符解释为四个空格,这意味着您的代码也正确缩进为 us ,甚至复制和粘贴办法。幸运的是,如果你小心的话,可以通过编辑按钮检查

解决方案:避免在Haskell代码中使用制表符,除非您确定如何避免陷阱。如果你要在stackoverflow上发布代码,那么无论如何都要避免它们。

(另一个答案解释了一些在修复缩进后需要纠正的事情。)