Skip to content

Instantly share code, notes, and snippets.

@hiteshjasani
Last active August 29, 2015 14:07
Show Gist options
  • Save hiteshjasani/135b186db1fe2eb6ab36 to your computer and use it in GitHub Desktop.
Save hiteshjasani/135b186db1fe2eb6ab36 to your computer and use it in GitHub Desktop.
Nim example of Haskell Maybe type
###############################
## Library code
type
TMaybeKind = enum
mkJust,
mkNothing
TMaybe[T] = object
case kind: TMaybeKind
of mkJust: val: T
of mkNothing: noVal: int
proc eval[T](a: TMaybe[T], justProc: proc (x: T), nothingProc: proc ()) =
case a.kind
of mkJust: justProc(a.val)
of mkNothing: nothingProc()
proc just[T](v: T): TMaybe[T] = TMaybe[T](kind: mkJust, val: v)
proc nothing(): TMaybe[int] = TMaybe[int](kind: mkNothing, noVal: 0)
###############################
## Application code
proc prVal[T](val: T) = echo "val is " & $val
proc prNo() = echo "no val"
let
a = just(7)
b = nothing()
c = just("hello world")
eval(a, prVal[int], prNo)
eval(b, prVal[int], prNo)
eval(c, prVal[string], prNo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment