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

问题描述 投票:3回答:2

GHC.Exts出口函数the

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

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

如何实现返回theMay的函数Maybe

haskell ghc
2个回答
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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.