Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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...)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top