Last active
December 2, 2018 08:33
-
-
Save brainrake/e24e9f83c25c661077498076a31e9244 to your computer and use it in GitHub Desktop.
Optional function arguments in Idris
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
interface Optional a t where | |
optional : t -> Maybe a | |
Optional a (Maybe a) where | |
optional x = x | |
Optional a a where | |
optional x = Just x | |
Optional a () where | |
optional _ = Nothing | |
Optional a (Either e a) where | |
optional (Right x) = Just x | |
optional _ = Nothing | |
f : Optional Integer t => t -> String | |
f x = | |
case the (Maybe Integer) (optional x) of | |
Just x => "number " ++ show x | |
Nothing => "nothing" | |
examples : List String | |
examples = | |
[ f 5 | |
, f (Just 3) | |
, f Nothing | |
, f () | |
, f (Left "lofasz") | |
, f (the (Either () Integer) (Right 4)) | |
] | |
default : Optional a t => a -> t -> a | |
default {a} def x = | |
case (the (Maybe a) (optional x)) of | |
Just x => x | |
Nothing => def | |
g : Optional Integer t => t -> String | |
g x = | |
"number " ++ show (default 0 x) | |
examples' : List String | |
examples' = | |
[ g 4 | |
, g Nothing | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment