-- Copyright 2013 Evan Laforge
-- This program is distributed under the terms of the GNU General Public
-- License 3.0, see COPYING or http://www.gnu.org/licenses/gpl-3.0.txt

-- | Extra utils for "Data.Set".
module Util.Set where
import qualified Data.Set as Set


-- | Find a key at or below the given one.
lookup_below :: Ord k => k -> Set.Set k -> Maybe k
lookup_below :: forall k. Ord k => k -> Set k -> Maybe k
lookup_below k
k Set k
set = case forall a. Ord a => a -> Set a -> (Set a, Bool, Set a)
Set.splitMember k
k Set k
set of
    (Set k
_, Bool
True, Set k
_) -> forall a. a -> Maybe a
Just k
k
    (Set k
below, Bool
False, Set k
_) -> forall k. Set k -> Maybe k
find_max Set k
below

-- | Safe versions of findMin and findMax.
find_min :: Set.Set k -> Maybe k
find_min :: forall k. Set k -> Maybe k
find_min Set k
set
    | forall a. Set a -> Bool
Set.null Set k
set = forall a. Maybe a
Nothing
    | Bool
otherwise = forall a. a -> Maybe a
Just (forall a. Set a -> a
Set.findMin Set k
set)

find_max :: Set.Set k -> Maybe k
find_max :: forall k. Set k -> Maybe k
find_max Set k
set
    | forall a. Set a -> Bool
Set.null Set k
set = forall a. Maybe a
Nothing
    | Bool
otherwise = forall a. a -> Maybe a
Just (forall a. Set a -> a
Set.findMax Set k
set)