I was confused by the lack of these functions in the interface for the Sequence type, since Data.List provides these functions. Is there an efficiency problem here, or is it just a lack of demand for these functions?
And since they're not part of Data.Sequence, how can I efficiently implement them for my purposes?
Here's what I came up with:
> let insertBy cmp x seq = let (s1,s2) = partition (\y -> cmp x y == GT) seq in (s1 |> x) >< s2
> let s = fromList [1,2,3,4,5]
> insertBy compare 2 s
fromList [1,2,2,3,4,5]
Or you can just ape the version for lists:
{-# LANGUAGE ViewPatterns #-}
module Main
where
import Data.Sequence
insertBy :: (a -> a -> Ordering) -> a -> Seq a -> Seq a
insertBy _ x (viewl -> EmptyL) = singleton x
insertBy cmp x ys@(viewl -> (y:<ys'))
= case cmp x y of
GT -> y <| insertBy cmp x ys'
_ -> x <| ys
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With