Haskell:用于操作列表列表的语法

时间:2018-04-23 22:48:13

标签: list haskell

我无法找到操作列表列表的正确语法。

这就是我所拥有的

> sumLsts :: [[a]] -> [[a]] -> [[a]]
> sumLsts [[]] [[]] = [[]]
> sumLsts [(x:xs):tx] [(y:ys):ty] = [((+) x y) : sumLsts xs ys] : sumLsts tx ty

以下是输入和输出示例

> sumLsts [[1,1,1], [1,10,20], [-3, -4, -2]] [[3,5,6],[2,3,4],[2,3,2]]
> [[4,6,7],[3,13,24],[-1,-1,0]]

我在想[(x:xs):tx]将(x:xs)视为单个列表,并且tx被视为以下列表。 Haskell似乎不同意。

以下是错误消息

Couldn't match expected type 'a' with actual type '[[a0]]'
'a' is a rigid type variable bound by
   the type signature for:
      sumLsts :: forall a. [[a]] -> [[a]] -> [[a]]
In the pattern: x : xs
In the pattern: (x : xs) : tx
In the pattern [(x : xs) : tx]
Relevant bindings include
   sumLsts :: [[a]] -> [[a]] -> [[a]]

1 个答案:

答案 0 :(得分:3)

正如对该问题的评论所指出的,(x:xs)[a]类型对象的模式,aInt,{{ 1}},String,甚至Bool本身就像[a]

在这种情况下,您的模式匹配应为:

[Int]

但请注意您的功能只是:

sumLsts ((x:xs):tx) ((y:ys):ty) = ...
{- to [[1, 3, 6], [2, 4, 7], [3, 5, 8]], ((x:xs): tx) matches:
   x  = 1
   xs = [3, 6]
   tx = [[2, 4, 7], [3, 5, 8]]
-}

sumLsts = zipWith (zipWith (+)) 将两个列表与连接函数配对,例如

zipWith

在这种情况下,您的外部两个列表会配对,因此每个子列表都是zipWith f [x1, x2, ..., xn] [y1, y2, ..., yn] = [ f x1 y1 , f x2 y2 , ... , f xn yn ] x。您尝试将这些与其他配对,因此y是另一个f,这次zipWith

zipWith (+)
相关问题