[英]Haskell: Syntax for manipulating a list of lists
我找不到用於處理列表列表的正確語法。
這就是我所擁有的
> 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]]
正如對該問題的評論所指出的那樣, (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 (+)
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] ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.