简体   繁体   English

Haskell:为什么“ Nothing <(4 :: Maybe Int)”得到一个错误,但是“ Nothing <Just 4”通过?

[英]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 StringMaybe 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 aEq实例中定义,由于它在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 xJust 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)给您一个错误,因为4Int (从技术上讲,它是Num类型类中的任何类型),但是4不是Maybe Int If you write 4 :: String or 4 :: [Int] or 4 :: Int -> Int you will get a similar type error. 如果您编写4 :: String4 :: [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.

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