Skip to content

Instantly share code, notes, and snippets.

@bradparker
Created March 2, 2021 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradparker/3523d4303d1f84b6d48f0a44b7e7b30e to your computer and use it in GitHub Desktop.
Save bradparker/3523d4303d1f84b6d48f0a44b7e7b30e to your computer and use it in GitHub Desktop.
Applicative record building from maps
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