Skip to content

Instantly share code, notes, and snippets.

@zbroyar
Created January 2, 2012 02:25
Show Gist options
  • Save zbroyar/1549036 to your computer and use it in GitHub Desktop.
Save zbroyar/1549036 to your computer and use it in GitHub Desktop.
Folding list of ADT items into pair of options
open Printf
type t = A of string * float | B of int * float
let l = [A ("a1", 0.); B (1, 1.); A ("a2", 1.1); A ("a3",1.2); B (2,1.1)]
let f = fun l ->
List.fold_left
(fun (a,b) it ->
match it,a,b with
| A (s,t), None, _ -> Some it, b
| A (s,t), Some (A (s',t')), _ -> if t > t' then Some it, b else a,b
| B (i,t), _, None -> a, Some it
| B (i,t), _, Some (B (i', t')) -> if t > t' then a, Some it else a,b
| _ -> a,b
) (None, None) l
let a,b = f l
let _ = match a with
| Some (A (s,t)) -> printf "%s -> %f\n" s t
| _ -> printf "None\n"
let _ = match b with
| Some (B (i,t)) -> printf "%d -> %f\n" i t
| _ -> printf "None\n" ;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment