Haskell:为什么"Nothing <(4 :: Maybe Int)"会出错,但"Nothing <Just 4"会通过?

sqd*_*sqd 0 haskell functional-programming

Nothing的类型可能是Maybe Int,为什么不能与另一个相比Maybe Int

为什么Nothing< Just 4通过?

Don*_*art 7

表达式中存在一个简单的类型错误: 4没有类型Maybe Int.

  • @sqd但是`Just 4 :: Maybe Int`有效. (3认同)

chi*_*chi 5

是的,Nothing可以是类型Maybe Int(或Maybe String,或Maybe AnythingElse).

Maybe Int可以比较任何两个类型的值.

平等==被定义为人们可能期望的:Nothing仅等于Nothing,并且Just x仅等于Just yif x==y.这是在Eq实例中定义的Maybe a,由于它在Haskell中,因此会自动导入Prelude.

同样,也有一个Ord (Maybe a)实例Prelude.这个实例定义<之间Maybe Int这么说Nothing是最小元素(<别的),而这两个值Just xJust y根据是否相比x < y.

所以,Nothing < Just 4是的.


代码Nothing<(4::Maybe Int)给你一个错误,因为4Int(从技术上说,这是任何类型的Num类型类),而4不是一个Maybe Int.如果你写4 :: String或者4 :: [Int]或者4 :: Int -> Int你会得到一个类似的错误类型.

Maybe Int类型仅包含值

Nothing
Just 0
Just 1
Just -1
Just 2
Just -2
...
Run Code Online (Sandbox Code Playgroud)

(还有一些底部,我省略了.)

该值4不是类型的值Maybe Int.Just 4而是一个这样的价值观.