Last active
September 23, 2016 08:47
-
-
Save cobalamin/f6a3dc7242ee86e11a6610012d491a06 to your computer and use it in GitHub Desktop.
playing around with making invalid Ints represented explicitly
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
module SafeInt exposing (SafeInt, fromInt, get, map, map2, andThen, (+!), (-!), (*!), (//!), (%!), (^!)) | |
type SafeInt | |
= Safe Int | |
| Invalid | |
fromInt : Int -> SafeInt | |
fromInt i = | |
if intIsNaN i || intIsInfinite i then | |
Invalid | |
else | |
Safe i | |
get : SafeInt -> Maybe Int | |
get si = | |
case si of | |
Invalid -> | |
Nothing | |
Safe i -> | |
Just i | |
infinity : Int | |
infinity = | |
floor (1 / 0) | |
negInfinity : Int | |
negInfinity = | |
floor (-1 / 0) | |
intIsNaN : Int -> Bool | |
intIsNaN x = | |
x /= x | |
intIsInfinite : Int -> Bool | |
intIsInfinite x = | |
x == infinity || x == negInfinity | |
map : (Int -> Int) -> SafeInt -> SafeInt | |
map f si = | |
case si of | |
Invalid -> | |
Invalid | |
Safe i -> | |
fromInt (f i) | |
map2 : (Int -> Int -> Int) -> SafeInt -> SafeInt -> SafeInt | |
map2 op x y = | |
case ( x, y ) of | |
( Safe x', Safe y' ) -> | |
fromInt (op x' y') | |
_ -> | |
Invalid | |
andThen : SafeInt -> (Int -> SafeInt) -> SafeInt | |
andThen si f = | |
case si of | |
Invalid -> | |
Invalid | |
Safe i -> | |
f i | |
andThen2 : (Int -> Int -> SafeInt) -> SafeInt -> SafeInt -> SafeInt | |
andThen2 f x y = | |
x | |
`andThen` | |
\x' -> | |
y | |
`andThen` | |
\y' -> | |
f x' y' | |
(+!) : SafeInt -> SafeInt -> SafeInt | |
(+!) = | |
map2 (+) | |
(-!) : SafeInt -> SafeInt -> SafeInt | |
(-!) = | |
map2 (-) | |
(*!) : SafeInt -> SafeInt -> SafeInt | |
(*!) = | |
map2 (*) | |
-- https://github.com/elm-lang/core/issues/590 | |
-- https://github.com/elm-lang/core/issues/92 | |
(//!) : SafeInt -> SafeInt -> SafeInt | |
(//!) = | |
andThen2 | |
(\x y -> | |
if y == 0 then | |
Invalid | |
else | |
(toFloat x / toFloat y) | |
|> floor | |
|> fromInt | |
) | |
-- https://github.com/elm-lang/core/issues/194 | |
(^!) : SafeInt -> SafeInt -> SafeInt | |
(^!) = | |
andThen2 | |
(\x y -> | |
if y < 0 then | |
Invalid | |
else | |
fromInt (x ^ y) | |
) | |
(%!) : SafeInt -> SafeInt -> SafeInt | |
(%!) = | |
map2 (%) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment