Created
May 19, 2018 19:10
-
-
Save alexpeits/ac4534d4968981a4b2760c2b2e9dac28 to your computer and use it in GitHub Desktop.
Get and set record fields dynamically using DataKinds
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
{-# LANGUAGE AllowAmbiguousTypes #-} -- GHC prompted me | |
{-# LANGUAGE KindSignatures #-} | |
{-# LANGUAGE FlexibleInstances #-} | |
{-# LANGUAGE DataKinds #-} | |
{-# LANGUAGE TypeApplications #-} -- required for the examples | |
module EnvAccess where | |
data EnvType = LocalEnv | GlobalEnv | |
data Env = Env {localEnv :: Int, globalEnv :: Int} deriving Show | |
env :: Env | |
env = Env 1 2 | |
class EnvGetSet (a :: EnvType) where | |
getEnv :: Env -> Int | |
setEnv :: Env -> Int -> Env | |
instance EnvGetSet LocalEnv where | |
getEnv = localEnv | |
setEnv e x = e {localEnv = x} | |
instance EnvGetSet GlobalEnv where | |
getEnv = globalEnv | |
setEnv e x = e {globalEnv = x} | |
-- getEnv @LocalEnv -> 1 | |
-- setEnv @LocalEnv 100 -> Env {localEnv = 100, globalEnv = 2} | |
-- getEnv @GlobalEnv -> 2 | |
-- setEnv @GlobalEnv 200 -> Env {localEnv = 1, globalEnv = 200} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment