Skip to content

Instantly share code, notes, and snippets.

@stoeffel
Last active June 8, 2016 10:21
Show Gist options
  • Save stoeffel/a398d844d5631c1df9277722087a75df to your computer and use it in GitHub Desktop.
Save stoeffel/a398d844d5631c1df9277722087a75df to your computer and use it in GitHub Desktop.
Predicate / Comparison in elm
import Html exposing (text, div, p)
-- based on https://medium.com/@drboolean/monoidal-contravariant-functors-are-actually-useful-1032211045c4#.r6oaoxdxd
-- Order
concatOrder : Order -> Order -> Order
concatOrder a b =
if a == EQ then
b
else
a
emptyOrder : Order
emptyOrder = EQ
-- Comparison
type Comparison a
= Comparison (a -> a -> Order)
compare : Comparison a -> a -> a -> Order
compare (Comparison f) =
f
concat : Comparison a -> Comparison a -> Comparison a
concat f g =
Comparison (\x y -> concatOrder (compare f x y) (compare g x y))
foldMap : List (a -> a -> Order) -> Comparison a
foldMap =
List.map Comparison >> List.foldr concat empty
empty : Comparison a
empty = Comparison (\_ _ -> emptyOrder)
contraMap : (a -> b) -> Comparison b -> Comparison a
contraMap f c =
Comparison (\x y -> compare c (f x) (f y))
-- COMPARISON EXAMPLES
eq21 a b =
if a == 21 then
GT
else if b == 21 then
LT
else
EQ
over21 a b =
if a > 21 then
LT
else if b > 21 then
GT
else
EQ
greater a b =
if a > b then
GT
else if b > a then
LT
else
EQ
blackjack = foldMap [eq21, over21, greater]
result = List.sortWith (compare blackjack) [15..25]
type alias Card =
{ suit: String
, val: Int
}
cards : List Card
cards = [ { suit = "hearts", val = 8 }
, { suit = "diamonds", val = 4 }
, { suit = "clubs", val = 7 }
]
rules = contraMap .val blackjack
result2 = List.sortWith (compare rules) cards
toText = toString >> text
main =
div []
[ p [] [toText result]
, p [] [toText result2]
]
import Html exposing (text)
-- based on https://medium.com/@drboolean/monoidal-contravariant-functors-are-actually-useful-1032211045c4#.r6oaoxdxd
-- PREDICATE
type Predicate a
= Predicate (a -> Bool)
run : Predicate a -> a -> Bool
run (Predicate f) =
f
concat : Predicate a -> Predicate a -> Predicate a
concat f g =
Predicate (\x -> run f x && run g x)
empty : Predicate a
empty = Predicate (always True)
foldMap : List (a -> Bool) -> Predicate a
foldMap =
List.map Predicate >> List.foldr concat empty
-- PREDICATE EXAMPLE
gt5 = \x -> x > 5
lt20 = \x -> x < 20
odd = \x -> x % 2 == 1
preds = foldMap [gt5, lt20, odd]
items = [0..30]
result = List.filter (run preds) items
main =
result
|> toString
|> text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment