我读过关于多态常量/空值多态函数in Learn You A Haskell的文章。它给出了几个内置的示例,例如:
ghci> 20 :: Float
20.0
ghci> 20 :: Int
20
ghci> minBound :: Int
-2147483648
ghci> maxBound :: (Bool, Int, Char)
(True,2147483647,'\1114111')
但是,它并没有解释如何定义您自己的。它们是如何定义的?
发布于 2012-02-01 07:50:37
你需要创建一个包含你想要的函数/常量的类型类,每个函数/常量都有一个变量返回类型。为您希望常量能够成为的每种类型实例化它。
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"
示例用法(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"
发布于 2012-02-04 09:37:58
首先,我建议不要使用术语“常量”来表示非函数,因为所有值都是常量(不可变),无论这些值是否为函数(即具有函数类型)。
你甚至不需要类型类来拥有多态的非函数。[]
就是一个例子。要定义您自己的多态非函数,您可以定义一个数据类型(如list示例中所示),或者使用已定义的片段构造一些内容。例如:empties = ([],[[]])
。
https://stackoverflow.com/questions/9088821
复制相似问题