2017-01-24 83 views
1

我能夠使用摺疊平鋪列表帶摺疊

flattenWithFold(Iterable list) => list.fold([], (List xs, s) { 
s is Iterable ? xs.addAll(flattenWithFold(s)) : xs.add(s); 
    return xs; 
}); 

弄平一個列表時執行

​​

它產生正確的結果[1,3,5,1,2,2,1 6]

但是當我嘗試重構使用..add,它產生不正確的結果

flattenWithFold1(Iterable list) => list.fold([], (List xs, s) => xs..add(
       s is Iterable ? xs.addAll(flattenWithFold1(s)) : s)); 

有人可以解釋執行時爲什麼有[null,null,2,1,null,6]爲空[1,3,5,1,2,null]

print(flattenWithFold1([1,[3,5,[1,2]],[2,1],6])); 

回答

4

你在你的結果獲得null因爲如果sIterable你正在做xs..add(xs.addAll(flattenWithFold1(s))addAllvoid方法,但由於您將它用作表達式,因此它將返回null。因此,您正在將平展元素添加到xs,但是隨後您將添加null,這是void方法的返回值。

+0

感謝您的解釋@哈里。有沒有一種有效的方法來使用摺疊而不使用返回?提前致謝。 –

+0

你只需要級聯addAll。我不確定爲什麼fold是一個需求,因爲你也可以做flatten(Iterable list)=> list.expand((item)=> item is Iterable?flatten(item):[item]); –

+0

使用expand是一種有效的方法。我只是試圖看看是否有另一種有效的摺疊方式。謝謝@Alan –