List Haskell:用于操作列表列表的语法
我很难找到操作列表的正确语法 这是我的List Haskell:用于操作列表列表的语法,list,haskell,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
> 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应该被看作是下面的列表。哈斯克尔似乎不同意
这是错误消息
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]]
正如在对这个问题的评论中指出的,
(x:xs)
是类型为[a]
的对象的模式,无论a
是否有Int
、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(+)
由于某些奇怪的原因,人们总是认为需要方括号来匹配任何列表中的模式。你不知道
[foo]
特别是一种模式,它将列表与一个元素完全匹配,无论foo
本身是否是另一种模式。要弹出任何非零列表的头部(即在本例中,2D列表的第一行),只需写入((x:xs):tx)
[[[]]
不是类型为[[a]]
的空列表;这是一个包含空列表的列表[]
是类型[a]
、[[a]]
、[[[a]]]
等的唯一空列表,无论类型嵌套有多深。这对我来说非常有效,谢谢!还有一个非常清晰的语法解释,所以加倍感谢!
zipWith (zipWith (+)) [[1,1,1], [1,10,20], [-3, -4, -2]] [[3,5,6],[2,3,4],[2,3,2]]
= [ [ 1, 1, 1] `zipWith (+)` [3, 5, 6]
, [ 1, 10, 20] `zipWith (+)` [2, 3, 4]
, [-3, -4, -2] `zipWith (+)` [2, 3, 2]]
= [ [ 1 + 3
, 1 + 5
, 1 + 6]
, [ 1 + 2
, 10 + 3
, 20 + 4]
, [ -3 + 2
, -4 + 3
, -2 + 2] ]