請注意,([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)
解決方案2讓他們所有的maxlength
:另寫zipWith功能不會停止。
我喜歡的解決方案2.讓我們來看看definition of zipWith
zipWith :: (a->b->c) -> [a]->[b]->[c]
zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
zipWith _ _ _ = [] -- here's the problem - it stops as soon as any list is empty
OK,讓我們不要再停:
zipWithMore :: (a -> a -> a) -> [a] -> [a] -> [a]
zipWithMore f (a:as) (b:bs) = f a b : zipWithMore f as bs
zipWithMore f [] bs = bs -- if there's more in bs, use that
zipWithMore f as [] = as -- if there's more in as, use that
現在你可以用zipWithMore (+)
取代zipWith (+)
。我會留下深刻的印象給你。
請明確說明你希望addLists [[1,2,3],[7,6,8],[0,3,4]]的結果是什麼。你的問題並不明顯。 – dave4420
看來你已經編輯了你的問題來澄清它,但我恐怕我還是不明白。 'addLists [[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