Skip to content

Instantly share code, notes, and snippets.

@hyone
Created September 4, 2012 02:44
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 hyone/3615967 to your computer and use it in GitHub Desktop.
Save hyone/3615967 to your computer and use it in GitHub Desktop.
Define function that accepts only specific multi data constructors on a type
{-# LANGUAGE GADTs #-}
data MyString
data MyInt
data MyNil
data MyData tag where
MyString :: String -> MyData MyString
MyInt :: Int -> MyData MyInt
MyNil :: MyData MyNil
class HasValue a
instance HasValue MyString
instance HasValue MyInt
-- accept all data constructor
test1 :: MyData a -> String
test1 (MyString s) = "MyString " ++ s
test1 (MyInt i) = "MyInt " ++ show i
test1 MyNil = "MyNil"
-- accept only data constructor that conform HasValue
test2 :: (HasValue a) => MyData a -> String
test2 _ = "test2"
{-
ghci> test1 (MyString "hello")
"MyString hello"
ghci> test1 (MyInt 22)
"MyInt 22"
ghci> test1 MyNil
"MyNil"
ghci> test2 (MyString "hello")
"test2"
ghci> test2 (MyInt 55)
"test2"
ghci> test2 MyNil
<interactive>:34:1:
No instance for (HasValue MyNil)
arising from a use of `test2'
Possible fix: add an instance declaration for (HasValue MyNil)
In the expression: test2 MyNil
In an equation for `it': it = test2 MyNil
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment