简体   繁体   English

为什么Data.Sequence没有`insert'或`insertBy',我该如何有效地实现它们呢?

[英]Why doesn't Data.Sequence have `insert' or `insertBy', and how do I efficiently implement them?

I was confused by the lack of these functions in the interface for the Sequence type, since Data.List provides these functions. 由于Data.List提供了这些函数,我对Sequence类型的接口中缺少这些函数感到困惑。 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? 由于它们不属于Data.Sequence,我如何才能有效地实现它们?

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: 或者你可以只是为列表的版本ape:

{-# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM