请注意,
([0]++)
与
(0:)
相同,这将使其看起来更整洁,并节省我们一两个纳秒的时间。
(我是在开玩笑关于纳秒的事情 - 没有人能够感觉到某件事情快了一个纳秒,但这样做更美好。)
让我们首先考虑如何创建所需的列表。我们想要:
postponeLists [[1,2,3], [7,6,8], [10,20,30,40]]
= [[1,2,3], [0,7,6,8], [0,0,10,20,30,40]]
= [1,2,3] : ones that should have zero in front of them
这就足够解释了:
postponeLists [] = []
postponeLists (l:ls) = l : map (0:) (postponeLists ls)
现在你说:
foldl (zipWith +) [] [[1,2,3],[0,7,6,8],[0,0,0,3,4]]
但是你的意思是什么?
foldl (zipWith (+)) [] [[1,2,3],[0,7,6,8],[0,0,0,3,4]]
不幸的是,这会给你[]
,因为zipWith
一旦其中任何一个列表用完元素就停止。
我们需要一种不停止的方法来合并它们。
解决方案1:找到最长的那个,使用take maxlength.(++ repeat 0)
使它们都成为maxlength
。
解决方案2:编写另一个不会停止的zipWith
函数。
我更喜欢解决方案2。让我们看看zipWith
的定义。
zipWith :: (a->b->c) -> [a]->[b]->[c]
zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
zipWith _ _ _ = []
好的,那我们继续吧:
好的,那我们就不停下来:
zipWithMore :: (a -> a -> a) -> [a] -> [a] -> [a]
zipWithMore f (a:as) (b:bs) = f a b : zipWithMore f as bs
zipWithMore f [] bs = bs
zipWithMore f as [] = as
现在你可以用
zipWithMore(+)
替换
zipWith(+)
。我会留下结论给你。
addLists [[1,2,3], [7,6,8], [0,3,4]]
的结果是什么。从您的问题中并不明显。 - dave4420addLists [[1,2,3], [7,6,8], [0,3,4]]
的结果应该是什么样子?您提供的示例foldl (zipWith +) [] [[1,2,3],[0,7,6,8],[0,0,0,3,4]]
无法通过类型检查,我无法弄清楚您的意图。 - mhwombat[1, 2+7, 3+6+0, 8+4, 4]
=[1,9,9,12,4]
吗? - mhwombat[1,2+7,3+6+0,8+3,4]
。 - Nathan Edwards