[Haskell-beginners] How to access non-exported function from Data.Set?

Ozgur Akgun ozgurakgun at gmail.com
Thu Jun 2 12:18:57 CEST 2011


I'll give this a try.

On 2 June 2011 02:06, Christoph Bussler <chbussler at aol.com> wrote:

> I’d like to find an element in a set. If the element is there, I’d like to
> get it back (not just the fact that it exists). If it is not in the set, I’d
> like to get the next higher and the next lower one (according to the sort
> order).


import Prelude hiding (null)
import Data.Set

-- if the given element is in the set, return it
-- else, try to return the (next lower, next higher)
-- (please ask if you do not understand why I chose this type)
foo :: Ord a => a -> Set a -> Either a (Maybe a, Maybe a)
foo x s = case splitMember x s of
    (_, True, _)   -> Left x
    (low, _, high) -> Right (findMaxMaybe low, findMinMaybe high)

-- *Main> foo 3 $ fromList [1..10]
-- Left 3
-- 
-- *Main> foo 3 $ fromList [4..10]
-- Right (Nothing,Just 4)
-- 
-- *Main> foo 3 $ fromList $ 2:[4..10]
-- Right (Just 2,Just 4)
-- 
-- *Main> foo 3 $ fromList $ []
-- Right (Nothing,Nothing)

findMinMaybe :: Set a -> Maybe a
findMinMaybe s
    | null s    = Nothing
    | otherwise = Just (findMin s)

findMaxMaybe :: Set a -> Maybe a
findMaxMaybe s
    | null s    = Nothing
    | otherwise = Just (findMax s)

HTH,
Ozgur
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110602/245bc3d8/attachment.htm>


More information about the Beginners mailing list