Haskell - 了解where和pattern匹配

时间:2017-09-23 14:13:33

标签: haskell functional-programming pattern-matching

我试图在haskell中创建一个sum函数。我这样做是为了更熟悉这门语言。我已将其定义为:

mysum :: [Integer] -> Integer
mysum lst = sm lst
  where 
    sm :: [Integer] -> Integer
    sm lst [] = 0
    sm lst [x:xs]=
      x + sm xs

想法是返回列表头部的值,+尾部反馈到函数中。我记得在F#中做了类似的事情,但我简直无法让它在haskell中工作。

The error im getting is:
sum.hs:5:5: error:
    • Couldn't match expected type ‘Integer’
                  with actual type ‘[[Integer]] -> Integer’
    • The equation(s) for ‘sm’ have two arguments,
      but its type ‘[Integer] -> Integer’ has only one
      In an equation for ‘mysum’:
          mysum lst
            = sm lst
            where
                sm :: [Integer] -> Integer
                sm lst [] = 0
                sm lst [x : xs] = x + sm xs
  |
5 |     sm lst [] = 0
  |     ^^^^^^^^^^^^^...

1 个答案:

答案 0 :(得分:7)

sm :: [Integer] -> Integer
   -- ^^^^^^^^^ one argument
sm lst [] = ...
-- ^^^ ^^ two arguments
sm lst [x:xs]= ...
-- ^^^ ^^^^^^ two arguments

您需要删除lst,并且只需对另一个参数进行模式匹配。

此外,(x:xs)不使用方括号。模式[x:xs]匹配单个元素列表,其中元素是非空列表x:xs - 您不想匹配列表列表。

因此可能的解决方法是:

mysum :: [Integer] -> Integer
mysum lst = sm lst
  where 
  sm :: [Integer] -> Integer
  sm [] = 0
  sm (x : xs) = x + sm xs

上面有一个冗余:mysumsm做同样的事情!因此,我们可以删除辅助定义。

mysum :: [Integer] -> Integer
mysum []       = 0
musum (x : xs) = x + mysum xs