Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining polymorphic constants in Haskell

I've read about polymorphic constants/nullary polymorphic functions in Learn You A Haskell. It gave several examples of built-in ones, such as:

ghci> 20 :: Float  
20.0  
ghci> 20 :: Int  
20  
ghci> minBound :: Int  
-2147483648  
ghci> maxBound :: (Bool, Int, Char)  
(True,2147483647,'\1114111')  

However, it does not explain how to define your own. How are they defined?

like image 476
Jeremy Avatar asked Jan 31 '12 23:01

Jeremy


1 Answers

You need to make a typeclass including the functions/constants you want, each with a variable return type. Instantiate it for each type you want your constants to be able to be.

class MyConstants a where
  one :: a
  ten :: a

instance MyConstants Int where
  one = 1
  ten = 10

instance MyConstants Float where
  one = 1.0
  ten = 10.0

instance MyConstants String where
  one = "one"
  ten = "ten"

Example Usage (codepad)

main = do
  putStrLn . show $ (ten :: Int)
  putStrLn . show $ (one :: String)
  putStrLn . show $ (ten :: Float) + one
  putStrLn . show $ "Count from " ++ one ++ " to " ++ ten
10
"one"
11.0
"Count from one to ten"
like image 69
4 revs Avatar answered Oct 27 '22 06:10

4 revs