I needed the split_on function while programming, I think the use case is not much, but still useful, thoughts on adding it to Roc Builtins is it worth?
split_on : List(item), (item, item -> Bool) -> List(List(item))
split_on = |items, fun| {
aux = |rest, inner_acc, acc| match rest {
[] => acc
[h] => acc.append(inner_acc.append(h))
[f, s, .. as t] => {
if (fun(f, s)) {
aux(t.prepend(s), inner_acc.append(f), acc)
} else {
aux(t.prepend(s), [], acc.append(inner_acc.append(f)))
}
}
}
aux(items, [], [])
}
expect [1, 2] |> split_on(|cur, next| cur.is_eq(next)) |> List.is_eq([[1], [2]])
expect [1, 1, 2] |> split_on(|cur, next| cur.is_eq(next)) |> List.is_eq([[1, 1], [2]])
expect [1, 1, 2, 3] |> split_on(|cur, next| cur.is_eq(next)) |> List.is_eq([[1, 1], [2], [3]])
Last updated: Oct 15 2026 at 17:56 UTC