[英]Defining polymorphic constants in Haskell
I've read about polymorphic constants/nullary polymorphic functions in Learn You A Haskell . 我已经在Learn You A Haskell中读到了关于多态常量/ nullary多态函数的内容。 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"
First, I recommend against using the term "constant" to mean non-functions, since all values are constant (immutable), whether those values are functions (ie have function type) or not. 首先,我建议不要使用术语“常量”来表示非函数,因为所有值都是常量(不可变),无论这些值是否为函数(即具有函数类型)。
You don't even need type classes to have polymorphic non-functions. 您甚至不需要类型类来具有多态非函数。 An example is
[]
. 一个例子是
[]
。 To define your own polymorphic non-functions, you can define a data type (as in the list example) or construct something out of already-defined pieces. 要定义自己的多态非函数,可以定义数据类型(如列表示例中所示)或使用已定义的片段构造某些内容。 For instance:
empties = ([],[[]])
. 例如:
empties = ([],[[]])
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.