Last active
August 29, 2015 14:07
-
-
Save hiteshjasani/135b186db1fe2eb6ab36 to your computer and use it in GitHub Desktop.
Nim example of Haskell Maybe type
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
############################### | |
## 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