Last active
June 24, 2021 10:20
-
-
Save idkjs/5d5f604cbb2e43a4805183c6ef27f492 to your computer and use it in GitHub Desktop.
Stdlib.Seq.re
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/**************************************************************************/ | |
/* */ | |
/* OCaml */ | |
/* */ | |
/* Simon Cruanes */ | |
/* */ | |
/* Copyright 2017 Institut National de Recherche en Informatique et */ | |
/* en Automatique. */ | |
/* */ | |
/* All rights reserved. This file is distributed under the terms of */ | |
/* the GNU Lesser General Public License version 2.1, with the */ | |
/* special exception on linking described in the file LICENSE. */ | |
/* */ | |
/**************************************************************************/ | |
/* Module [Seq]: functional iterators */ | |
type node(+'a) = | |
| Nil | |
| Cons('a, t('a)) | |
and t('a) = unit => node('a); | |
let empty = () => Nil; | |
let return = (x, ()) => Cons(x, empty); | |
let cons = (x, next, ()) => Cons(x, next); | |
let rec append = (seq1, seq2, ()) => | |
switch (seq1()) { | |
| Nil => seq2() | |
| Cons(x, next) => | |
Cons(x, append(next, seq2)) | |
}; | |
let rec map = (f, seq, ()) => | |
switch (seq()) { | |
| Nil => Nil | |
| Cons(x, next) => | |
Cons(f(x), map(f, next)) | |
}; | |
let rec filter_map = (f, seq, ()) => | |
switch (seq()) { | |
| Nil => Nil | |
| Cons(x, next) => | |
switch (f(x)) { | |
| None => filter_map(f, next, ()) | |
| Some(y) => Cons(y, filter_map(f, next)) | |
} | |
}; | |
let rec filter = (f, seq, ()) => | |
switch (seq()) { | |
| Nil => Nil | |
| Cons(x, next) => | |
if (f(x)) { | |
Cons(x, filter(f, next)); | |
} else { | |
filter(f, next, ()); | |
} | |
}; | |
let rec concat = (seq, ()) => | |
switch (seq()) { | |
| Nil => Nil | |
| Cons(x, next) => append(x, concat(next), ()) | |
}; | |
let rec flat_map = (f, seq, ()) => | |
switch (seq()) { | |
| Nil => Nil | |
| Cons(x, next) => append(f(x), flat_map(f, next), ()) | |
}; | |
let concat_map = flat_map; | |
let fold_left = (f, acc, seq) => { | |
let rec aux = (f, acc, seq) => | |
switch (seq()) { | |
| Nil => acc | |
| Cons(x, next) => | |
let acc = f(acc, x); | |
aux(f, acc, next); | |
}; | |
aux(f, acc, seq); | |
}; | |
let iter = (f, seq) => { | |
let rec aux = seq => | |
switch (seq()) { | |
| Nil => () | |
| Cons(x, next) => | |
f(x); | |
aux(next); | |
}; | |
aux(seq); | |
}; | |
let rec unfold = (f, u, ()) => | |
switch (f(u)) { | |
| None => Nil | |
| Some((x, u')) => Cons(x, unfold(f, u')) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://sketch.sh/s/VYyUxvoyW1J6Db6UaUXNKa/