Skip to content

Instantly share code, notes, and snippets.

@idkjs
Created July 1, 2021 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idkjs/4ec9646a042c75b605ff169874979354 to your computer and use it in GitHub Desktop.
Save idkjs/4ec9646a042c75b605ff169874979354 to your computer and use it in GitHub Desktop.
GroupWhile for Rescript/Reason using Belt lib
type nonrec t('a) = list('a);
let rec dropWhile = (t, ~f) =>
switch (t) {
| [] => []
| [x, ...rest] =>
if (f(x)) {
dropWhile(rest, ~f);
} else {
t;
}
};
let takeWhile = (t, ~f) =>
{
let rec takeWhileHelper = (acc, t) =>
switch (t) {
| [] => Belt.List.reverse(acc)
| [x, ...rest] =>
if (f(x)) {
takeWhileHelper([x, ...acc], rest);
} else {
Belt.List.reverse(acc);
}
};
takeWhileHelper([], t);
};
let span = (t, ~f) =>
switch (t) {
| [] => ([], [])
| _ => (takeWhile(t, ~f), dropWhile(t, ~f))
};
let groupWhile = (t, ~f) =>
{
let rec groupWhileHelper = (t, ~f) =>
switch (t) {
| [] => []
| [x, ...rest] =>
let (ys, zs) = span(rest, ~f=f(x));
[[x, ...ys], ...groupWhileHelper(zs, ~f)];
};
groupWhileHelper(t, ~f);
};
@idkjs
Copy link
Author

idkjs commented Jul 1, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment