Created
March 2, 2021 23:45
-
-
Save bradparker/3523d4303d1f84b6d48f0a44b7e7b30e to your computer and use it in GitHub Desktop.
Applicative record building from maps
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 Main where | |
import Data.Foldable (traverse_) | |
import Data.Functor.Compose (Compose (Compose, getCompose)) | |
import Data.Map (Map) | |
import qualified Data.Map as Map | |
data Person = Person | |
{ id :: Int, | |
name :: String, | |
age :: Int | |
} | |
deriving (Show) | |
names :: Map Int String | |
names = Map.fromList [(1, "Alice"), (2, "Bob")] | |
ages :: Map Int Int | |
ages = Map.fromList [(1, 32), (2, 23)] | |
person :: Int -> (Map Int String, Map Int Int) -> Maybe Person | |
person i = | |
getCompose | |
( Person i | |
<$> Compose (Map.lookup i . fst) | |
<*> Compose (Map.lookup i . snd) | |
) | |
-- >>> main | |
-- Just (Person {id = 1, name = "Alice", age = 32}) | |
-- Just (Person {id = 2, name = "Bob", age = 23}) | |
-- Just (Person {id = 1, name = "Alice", age = 32}) | |
-- Just (Person {id = 2, name = "Bob", age = 23}) | |
main :: IO () | |
main = do | |
print $ person 1 (names, ages) | |
print $ person 2 (names, ages) | |
traverse_ (print . flip person (names, ages)) [1, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment