这包括两个问题,一个非常标准的问题(展平列表),然后充分连接字符串。
flatten(Iterable l) => l.fold([], (List list, element) {
if (element is Iterable)
list.addAll(flatten(element));
else
list.add(element);
return list;
});
concat(Iterable l) => l.fold([], (List list, element) {
if (element is String && !list.isEmpty && list.last is String)
list.add(list.removeLast() + element);
else
list.add(element);
return list;
});
void main() {
var nested = [ 'a', 'w', ['e', ['f', new Object(), 'f'], 'g'], 't', 'e'];
print(concat(flatten(nested));
}
更新:
另一个concat,灵感来自 Greg Lowe(与我的“大”和他的完全一样,但更简洁):
concat(Iterable list) => list.fold([], (List xs, x) => xs..add(
x is String && !xs.isEmpty && xs.last is String ? xs.removeLast() + x : x));
你可以随意组合他和我的功能,他们做的事情完全一样。