在Gleam中如何按元素拆分列表?
数据小陈
结论
按你给出的函数名和语义,Gleam 标准库没有可直接调用的 split_by_elem 函数;可以用 gleam/list 的 fold 或手写递归实现。实现时维护两个累加器:已经完成的块 chunks 和当前正在构建的块 current。遇到分隔元素时,如果 current 非空,就把它反转后加入 chunks,并清空 current;遇到普通元素则把它 cons 到 current。最后再处理一次 current,并把 chunks 反转回正确顺序。
实现步骤
- 因为泛型参数要能比较相等,所以加
where a: Eq约束。 - 用
#(chunks, current)作为累加器;current按逆序累积,最后用list.reverse恢复顺序。 - 分隔元素连续出现时不要产生空块,这和你给出的
[0,0,0] -> []一致。 - 遍历结束后,如果
current非空,仍要把它加入结果。 - 返回前把
chunks反转,避免使用append在末尾反复追加。
代码示例
import gleam/list
pub fn split_by_elem(list: List(a), element: a) -> List(List(a))
where a: Eq
{
let #(reversed_chunks, current) =
list.fold(
over: list,
from: #([], []),
with: fn(acc, item) {
let #(chunks, current) = acc
case item == element {
True ->
case current {
[] -> #(chunks, [])
_ -> #([list.reverse(current), ..chunks], [])
}
False -> #(chunks, [item, ..current])
}
},
)
let chunks = case current {
[] -> reversed_chunks
_ -> [list.reverse(current), ..reversed_chunks]
}
list.reverse(chunks)
}
注意事项
- 上面的实现会丢弃空块;如果你希望保留连续分隔元素产生的空段,需要修改
True分支,让它无条件把current加入chunks。 current采用 cons 累积,所以需要list.reverse;Gleam 的列表不可变,这种写法很常见。- 时间复杂度是 O(n),空间复杂度也是 O(n)。不要用
list.append在结果末尾反复追加,否则容易退化为 O(n²)。 - 如果列表元素类型不能比较相等,需要先调整数据结构或比较逻辑;
where a: Eq约束就是给==用的。
备注:内容仅供参考。
