[英]Haskell: Why “Nothing<(4::Maybe Int)” gets an error but “Nothing< Just 4” pass?
Nothing
's type could be Maybe Int
and why couldn't it be compared with another Maybe Int
? Nothing
类型可能是Maybe Int
,为什么不能将其与另一个Maybe Int
进行比较?
And why Nothing< Just 4
pass? 以及为什么
Nothing< Just 4
关?
表达式中有一个简单的类型错误: 4
没有类型Maybe Int
。
Yes, Nothing
can be of type Maybe Int
(or Maybe String
, or Maybe AnythingElse
). 是的,
Nothing
的类型不能为Maybe Int
(或Maybe String
或Maybe AnythingElse
)。
Any two values of type Maybe Int
can be compared. 可以比较
Maybe Int
类型的任何两个值。
Equality ==
is defined as one might expect: Nothing
is only equal to Nothing
, and Just x
is only equal to Just y
if x==y
. ==
的定义符合人们的预期: Nothing
仅等于Nothing
,并且x==y
Just x
仅等于Just y
x==y
。 This is defined in the Eq
instance for Maybe a
, which is automatically imported since it is in the Haskell Prelude
. 这在
Maybe a
的Eq
实例中定义,由于它在Haskell Prelude
,因此会自动导入。
Similarly, there is an Ord (Maybe a)
instance as well in the Prelude
. 同样,
Prelude
也有一个Ord (Maybe a)
实例。 This instance defines <
between Maybe Int
s so that Nothing
is the minimum element ( <
anything else), while two values Just x
and Just y
are compared according to whether x < y
. 该实例在
Maybe Int
之间定义<
,因此Nothing
是最小元素( <
其他),而根据x < y
是否比较两个值Just x
和Just y
x < y
。
So, Nothing < Just 4
is true. 因此,
Nothing < Just 4
。
The code Nothing<(4::Maybe Int)
gives you an error since 4
is an Int
(technically, it is any type in the Num
type class), but 4
is not a Maybe Int
. 代码
Nothing<(4::Maybe Int)
给您一个错误,因为4
是Int
(从技术上讲,它是Num
类型类中的任何类型),但是4
不是Maybe Int
。 If you write 4 :: String
or 4 :: [Int]
or 4 :: Int -> Int
you will get a similar type error. 如果您编写
4 :: String
或4 :: [Int]
或4 :: Int -> Int
您将得到类似的类型错误。
The Maybe Int
type contains only the values Maybe Int
类型仅包含值
Nothing
Just 0
Just 1
Just -1
Just 2
Just -2
...
(and some bottoms, which I omit.) (和一些底部,我忽略了。)
The value 4
is not a value of type Maybe Int
. 值
4
不是Maybe Int
类型的值。 Just 4
is instead one of such values. 相反,
Just 4
是此类值之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.