繁体   English   中英

在Haskell中定义多态常量

[英]Defining polymorphic constants in Haskell

我已经在Learn You A Haskell中读到了关于多态常量/ nullary多态函数的内容。 它提供了几个内置的例子,例如:

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

但是,它没有解释如何定义自己的。 他们是如何定义的?

你需要创建一个类型类,包括你想要的函数/常量,每个都有一个变量返回类型。 为您希望常量可以使用的每种类型实例化它。

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"

首先,我建议不要使用术语“常量”来表示非函数,因为所有值都是常量(不可变),无论这些值是否为函数(即具有函数类型)。

您甚至不需要类型类来具有多态非函数。 一个例子是[] 要定义自己的多态非函数,可以定义数据类型(如列表示例中所示)或使用已定义的片段构造某些内容。 例如: empties = ([],[[]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM