문제

GHC.Exts exports the function the:

the ensures that all the elements of the list are identical and then returns that unique element

This function is partial as it throws an error in case not all elements of the list are equal.

How can I implement a function theMay that returns a Maybe instead?

도움이 되었습니까?

해결책

the is defined as follows:

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"

Based on this we can directly deduce theMay:

theMay :: Eq a => [a] -> Maybe a
theMay (x:xs)
  | all (x ==) xs = Just x
  | otherwise     = Nothing
theMay []         = Nothing

다른 팁

Same thing, but using the 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

(Apologies for golfing in your Q&A...)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top