Last active
May 26, 2016 20:59
-
-
Save stoeffel/21b0d1a316edf76a7994c906b7006d5a to your computer and use it in GitHub Desktop.
data.these in elm
This file contains 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
import Html exposing (..) | |
type These a b | |
= This a | |
| That b | |
| Both a b | |
| Neither | |
toThese : Maybe a -> Maybe a -> These a a | |
toThese x y = | |
case x of | |
Just x -> | |
case y of | |
Just y -> | |
Both x y | |
Nothing -> | |
This x | |
Nothing -> | |
case y of | |
Just y -> | |
That y | |
Nothing -> | |
Neither | |
map : (a -> b) -> These a a -> These b b | |
map f these = | |
case these of | |
This x -> | |
This (f x) | |
That y -> | |
That (f y) | |
Both x y -> | |
Both (f x) (f y) | |
Neither -> | |
Neither | |
mapThis : (a -> a) -> These a a -> These a a | |
mapThis f these = | |
case these of | |
This x -> | |
This (f x) | |
Both x y -> | |
Both (f x) y | |
_ -> | |
these | |
mapThat : (a -> a) -> These a a -> These a a | |
mapThat f these = | |
case these of | |
That x -> | |
That (f x) | |
Both x y -> | |
Both x (f y) | |
_ -> | |
these | |
andThen : These a a -> (Maybe a -> Maybe a -> These b b) -> These b b | |
andThen these f = | |
case these of | |
This x -> | |
f (Just x) Nothing | |
That y -> | |
f Nothing (Just y) | |
Both x y -> | |
f (Just x) (Just y) | |
Neither -> | |
Neither | |
-- EXAMPLES | |
toBoth : Maybe number -> Maybe number -> These number number | |
toBoth x y = | |
toThese x x | |
this42 = | |
toThese (Just 42) Nothing | |
this3 = | |
toThese (Just 3) Nothing | |
that3 = | |
toThese Nothing (Just 3) | |
both3 = | |
toThese (Just 3) (Just 3) | |
neither3 = | |
toThese Nothing Nothing | |
type alias Person = | |
{ name: String | |
, age: These Int String | |
} | |
tom = Person "Tom" (That "unknown") | |
sue = Person "Sue" (This 12) | |
max = Person "Max" (Both 20 "more or less") | |
main = | |
let | |
patternMatching person = | |
case person.age of | |
This x -> | |
person.name ++ " is " ++ toString x | |
That y -> | |
person.name ++ "'s age is " ++ y | |
Both x y -> | |
person.name ++ " is " ++ toString x ++ " " ++ y | |
Neither -> | |
"nope" | |
in | |
div [] | |
[ asList | |
[ this3 | |
, that3 | |
, both3 | |
, mapThis ((*) -1) both3 | |
, mapThat ((*) -1) both3 | |
, map ((*) -1) both3 | |
, neither3 | |
, this42 `andThen` toBoth | |
] | |
, br [] [] | |
, p [] [ text (patternMatching tom)] | |
, p [] [ text (patternMatching sue)] | |
, p [] [ text (patternMatching max)] | |
] | |
asList list = | |
list | |
|> mapToLi | |
|> ul [] | |
mapToLi list = | |
list | |
|> List.map (toString) | |
|> List.map (\x -> [ text x ]) | |
|> List.map (li []) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment