Skip to content

Instantly share code, notes, and snippets.

@SPY
Last active November 3, 2015 09:06
Show Gist options
  • Save SPY/ddb5ec1d29e0cedaa12d to your computer and use it in GitHub Desktop.
Save SPY/ddb5ec1d29e0cedaa12d to your computer and use it in GitHub Desktop.
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
-- works too
class Message params msg | msg -> params, params -> msg where
create :: params -> msg
data FooMessage = FooMessage { from, to :: Int } deriving (Show)
data FooMessageParams = FooMessageParams { _from, _to :: Maybe Int }
instance Message FooMessageParams FooMessage where
create (FooMessageParams from to) = FooMessage (fromMaybe 0 from) (fromMaybe 0 to)
showMessage :: (Message params msg, Show msg) => msg -> String
showMessage = show
fooStr :: String
fooStr = showMessage $ create $ FooMessageParams Nothing Nothing
{-# LANGUAGE TypeFamilies #-}
class Message a where
type Params a :: *
create :: Params a -> a
data FooMessage = FooMessage { from, to :: Int } deriving (Show)
data FooMessageParams = FooMessageParams { _from, _to :: Maybe Int }
instance Message FooMessage where
type Params FooMessage = FooMessageParams
create (FooMessageParams from to) = FooMessage (fromMaybe 0 from) (fromMaybe 0 to)
showMeesage :: (Message msg, Show msg) => msg -> String
showMeesage = show
fooStr :: String
fooStr = showMeesage $ create $ FooMessageParams Nothing Nothing
{-
Couldn't match expected type ‘Params r0’
with actual type ‘FooMessageParams’
The type variable ‘r0’ is ambiguous
In the second argument of ‘($)’, namely
‘FooMessageParams Nothing Nothing’
In the second argument of ‘($)’, namely
‘create $ FooMessageParams Nothing Nothing’
-}
{-# LANGUAGE TypeFamilies #-}
class Message a where
data Params a :: *
create :: Params a -> a
data FooMessage = FooMessage { from, to :: Int } deriving (Show)
data FooMessageParams = FooMessageParams { _from, _to :: Maybe Int }
instance Message FooMessage where
data Params FooMessage = FP FooMessageParams
create (FP (FooMessageParams from to)) = FooMessage (fromMaybe 0 from) (fromMaybe 0 to)
showMeesage :: (Message msg, Show msg) => msg -> String
showMeesage = show
fooStr :: String
fooStr = showMeesage $ create $ FP $ FooMessageParams Nothing Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment