Last active
January 4, 2016 23:26
-
-
Save rizo/11cb81a501bca7b65afc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| open Elements | |
| type ('a, 'state) step = 'state -> 'a -> [ `Continue of 'state | `Stop of 'state ] | |
| type ('a, 'b, 'state) transducer = | |
| ('b, 'state) step -> ('a, 'state) step | |
| let map f = | |
| fun step -> fun r x -> | |
| step r (f x) | |
| let filter p = | |
| fun step -> fun r x -> | |
| if p x then step r x else `Continue r | |
| let take n = | |
| fun step -> | |
| let count = ref 0 in | |
| fun r x -> | |
| if !count < n | |
| then (incr count; step r x) | |
| else `Stop r | |
| let compose t1 t2 = | |
| fun xf -> (t1 (t2 xf)) | |
| let (>>) = compose | |
| let transduce_list t xs = | |
| List.rev (List.fold_until | |
| ~f:(t (fun xs x -> `Continue (x :: xs))) | |
| ~init:[] xs) | |
| let test () = | |
| assert (transduce_list (map ((+) 5) >> take 10) (List.range 0 5) | |
| = [5; 7; 9]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment