Skip to content

Instantly share code, notes, and snippets.

@margnus1
Created January 29, 2013 13:46
Show Gist options
  • Select an option

  • Save margnus1/4664349 to your computer and use it in GitHub Desktop.

Select an option

Save margnus1/4664349 to your computer and use it in GitHub Desktop.
Piping operators for operations that can fail
infix 1 |> !> !?>
fun v |> f = f v
fun NONE !> _ = NONE
| (SOME v) !> f = f v
fun NONE !?> _ = NONE
| (SOME v) !?> f = SOME (f v)
(* Example usage: *)
fun isqrt n =
let val r = n |> real |> Math.sqrt |> round
in if r * r = n then SOME r
else NONE
end;
"123s" |> Int.fromString !?> (fn i => i * i) !> isqrt; (* = SOME 123 *)
"lulz" |> Int.fromString !?> (fn i => i * i) !> isqrt; (* = NONE *)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment