GHC.Exts
出口函数the
:
the
确保列表中的所有元素都相同,然后返回该唯一元素
此函数是部分函数,因为如果列表中的所有元素都不相等,则会抛出错误。
如何实现返回theMay
的函数Maybe
?
the
定义如下:
the :: Eq a => [a] -> a
the (x:xs)
| all (x ==) xs = x
| otherwise = error "GHC.Exts.the: non-identical elements"
the [] = error "GHC.Exts.the: empty list"
基于此,我们可以直接推导出theMay
:
theMay :: Eq a => [a] -> Maybe a
theMay (x:xs)
| all (x ==) xs = Just x
| otherwise = Nothing
theMay [] = Nothing
同样的事情,但使用Maybe
monad:
import Data.Maybe (listToMaybe)
import Control.Monad (guard)
theMay :: Eq a => [a] -> Maybe a
theMay xs = do
x <- listToMaybe xs
guard $ all (x ==) xs
return x
(在你的问答中打高尔夫球道歉......)