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?
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With