Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save Porges/489230e3760404129359 to your computer and use it in GitHub Desktop.

Select an option

Save Porges/489230e3760404129359 to your computer and use it in GitHub Desktop.
// direct-ish translation
let allOrNone (xs : 'a option list) : 'a list option =
List.foldBack
(fun x st -> x |> Option.bind (fun x -> st |> Option.bind (fun st -> Some (x::st))))
xs
(Some [])
// shorter
let allOrNone2 (xs : 'a option list) : 'a list option =
List.foldBack
(fun x -> Option.bind (fun st -> x |> Option.map (fun x -> x::st)))
xs
(Some [])
// bails out early
let allOrNone3 xs =
let rec recAllOrNone cont = function
| (Some x :: xs) -> recAllOrNone (fun r -> cont (x :: r)) xs
| (None :: _) -> None
| _ -> cont []
recAllOrNone Some xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment