سؤال

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