Skip to content

Instantly share code, notes, and snippets.

@StevenXL
Created June 12, 2018 13:23
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 StevenXL/d11a81554230f46cfeca463472a3d017 to your computer and use it in GitHub Desktop.
Save StevenXL/d11a81554230f46cfeca463472a3d017 to your computer and use it in GitHub Desktop.
Kleisli Composition
module KleisliComposition where
import Data.Map (Map)
import qualified Data.Map as M
import Control.Monad ((<=<))
type UserName = String
type GamerID = Int
type PlayerCredits = Int
users :: [UserName]
users = ["nYarlathoTep", "KINGinYELLOW", "dagon1997", "rcarter1919", "xCTHULHUx", "yogSOThoth"]
ids :: [GamerID]
ids = [1..6]
credits :: [PlayerCredits]
credits = [2000, 15000, 300, 12, 50000, 150000]
userNameDB :: Map GamerID UserName
userNameDB = M.fromList $ zip ids users
creditsDB :: Map UserName PlayerCredits
creditsDB = M.fromList $ zip users credits
userFromID :: GamerID -> Maybe UserName
userFromID = flip M.lookup userNameDB -- notice use of flip so we can partially apply the DB
creditsFromUser :: UserName -> Maybe PlayerCredits
creditsFromUser = flip M.lookup creditsDB -- notice use of flip so we can partially apply the DB
creditsFromId :: GamerID -> Maybe PlayerCredits
creditsFromId = creditsFromUser <=< userFromID -- Kleisli composition; fancy name for composing monad factories
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment