Created
September 4, 2012 02:44
-
-
Save hyone/3615967 to your computer and use it in GitHub Desktop.
Define function that accepts only specific multi data constructors on a type
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 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