Skip to content

Instantly share code, notes, and snippets.

@naoto-ogawa
Created March 31, 2019 08:18
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 naoto-ogawa/2f477e55fecc1802ef3052b0f6214bc1 to your computer and use it in GitHub Desktop.
Save naoto-ogawa/2f477e55fecc1802ef3052b0f6214bc1 to your computer and use it in GitHub Desktop.
Variant sample
{-# LANGUAGE TypeOperators, DataKinds, OverloadedLabels, FlexibleContexts, GADTs #-}
import Data.Extensible
--
-- standard
--
data A = AX | AY deriving (Show, Eq)
data B = BY | BZ deriving (Show, Eq)
data AB = A A | B B deriving (Show, Eq)
printAB1 ab =
case ab of
A v -> case v of
AX -> "AX is selected"
AY -> "AY is selected"
B v -> case v of
BY -> "BY is selected"
BZ -> "BZ is selected"
printAB2 (A AX) = "AX is selected"
printAB2 (A AY) = "AY is selected"
printAB2 (B BY) = "BY is selected"
printAB2 (B BZ) = "BZ is selected"
ex1 :: AB
ex1 = A AX
ex2 :: AB
ex2 = B BZ
--
-- variant
--
type AB' = Variant '["a" >: A, "b" >: B]
printAB' :: AB' -> String
printAB' =
matchField
$ #a @= (\v -> case v of
AX -> "AX is selected"
AY -> "AY is selected"
)
<: #b @= (\v -> case v of
BY -> "BY is selected"
BZ -> "BZ is selected"
)
-- <: #c @= (\x -> show x) .... type checked
<: nil
ex1' :: AB'
ex1' = embedAssoc $ #a @= AX
ex2' :: AB'
ex2' = embedAssoc $ #b @= BZ
@naoto-ogawa
Copy link
Author

printAB1 ex1
"AX is selected"
printAB2 ex1
"AX is selected"
printAB' ex1'
"AX is selected"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment