实施可能版本的GHC.Exts''功能

时间:2014-03-27 19:16:39

标签: haskell ghc

GHC.Exts导出函数the

  

the确保列表中的所有元素都相同,然后返回该唯一元素

此函数是部分函数,​​因为如果列表中的所有元素都不相等则会抛出错误。

如何实现返回theMay的函数Maybe

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

同样的事情,但使用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

(在你的Q&amp; A ......打高尔夫球道歉)