在用 Haskell 进行函数式思考(第 45 页)中,Richard Bird 说有 6 个类型为 的函数Maybe a -> Maybe a
,尽管他只提到了 5 个。
应用于
Nothing
函数只能返回Nothing
或undefined
。应用于Just x
函数只能返回Nothing
orJust x
或undefined
。关键是我们对底层类型一无所知,因此无法发明新值。这总共有六种可能的功能。
我数了七:
first, second, third, fourth, fifth, sixth, seventh :: Maybe a -> Maybe a
first (Just x) = Just x
second (Just x) = Nothing
third (Just x) = undefined
fourth Nothing = Nothing
fifth Nothing = undefined
sixth undefined = Nothing
seventh undefined = undefined
一个相关的难题是,当我尝试将其中三个定义放在一个函数下时,我收到编译错误“模式匹配是多余的”。删除三行中的任何一行都会使其消失
foo :: Maybe a -> Maybe a
foo (Just x) = Nothing
foo Nothing = undefined
foo undefined = Nothing
你的函数不是全部函数,每次都取一种情况。这意味着没有覆盖的情况下,会出现错误。
所以本质上如果你写:
这是:
因此,您需要涵盖两种组合的情况:
Just x
, 或Nothing
,从而乘以每种情况的可能性。另一个问题是
undefined
insixth undefined = Nothing
不检查该项是否未定义:它只是一个名为 的变量undefined
。所以它相当于sixth x = Nothing
.因此,这基本上给我们留下了
Just x
:Just x
和/的三个选项Nothing
,以及:和 undefined 的两个选项,所以:undefined
error
Nothing
Nothing
然而,这些并不是所有选项:对于这两种情况中的任何一种,您也可以返回
Just undefined
(或)。Just (error "<undefined>")
我将这些作为练习列出。