由于Data.List提供了这些函数,我对Sequence类型的接口中缺少这些函数感到困惑。这里是否存在效率问题,或者仅仅缺乏对这些功能的需求?
由于它们不属于Data.Sequence,我如何才能有效地实现它们呢?
答案 0 :(得分:4)
以下是我提出的建议:
> 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]
或者您可以为列表的版本模仿:
{-# 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