Last active
November 23, 2020 21:47
-
-
Save bond15/6f9a4822a5f0c646814d738c6f613ec9 to your computer and use it in GitHub Desktop.
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
data Term a b where | |
Map :: (a -> b) -> Term a b | |
Filter :: (a -> Maybe a) -> Term a (Maybe a) | |
fuseMap :: Term a b -> Term b c -> Term a c | |
fuseMap (Map f ) (Map g) = Map $ g . f | |
filterFuse :: Term a (Maybe a) -> Term a b -> Term a (Maybe b) | |
filterFuse (Filter p) (Map f ) = Map (\x -> p x >>= Just . f) | |
fuseFilter :: Term a b -> Term b (Maybe b) -> Term a (Maybe b) | |
fuseFilter (Map f) (Filter p) = Map $ p . f | |
-- infix syntax | |
(||) = fuseMap | |
(>|) = filterFuse | |
(|>) = fuseFilter | |
filter p = Filter $ \x -> case p x of | |
True -> Just x | |
_ -> Nothing | |
map :: (a -> b) -> Term a b | |
map = Map | |
run :: Term a b -> [a] -> [b] | |
run (Map f) xs = fmap f xs | |
-- example | |
run (map (+1) || map (^2) |> filter even) [1..6] ==> [Just 4,Nothing,Just 16,Nothing,Just 36,Nothing] | |
-- This is a chain of list operations | |
(map (+1) || map (^2) |> filter even) | |
-- It reduces down to a single pass | |
Map (\x -> case (even ((x+1)^2)) of | |
True -> Just x | |
_ -> Nothing ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment