繁体   English   中英

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

[英]Implementing Maybe version of GHC.Exts 'the' function

GHC.Exts导出函数the

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

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

如何实现一个返回Maybe的函数theMay呢?

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"

基于此我们可以直接推断出5 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

(在你的问答中打高尔夫球道歉......)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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