Standard queue package for Haskell? [closed]

2020-07-27 03:15发布

Is there a standard queue implementation for Haskell? I see several reasonably mature priority queue implementations, but no simple queues. Data.Sequence seems OK, but I assume we could get better performance with a more restricted datatype. Further, restricting the operations (ie, not a deque) can prevent bugs from dequeuing from the wrong end.

Edit:

To clarify, I was hoping for a mature Haskell implementation, preferably in Haskell Platform or Hackage.

标签: haskell queue
2条回答
别忘想泡老子
2楼-- · 2020-07-27 03:40

Data.Queue was added to base in ghc 6.4 [1] and deprecated in ghc 6.6 [2] when it was subsumed by Data.Sequence.

From the 6.6 release notes:

There is a new module Data.Sequence for finite sequences. The Data.Queue module is now deprecated in favour of this faster, more featureful replacement.

[1] https://downloads.haskell.org/~ghc/6.4/docs/html/users_guide/release-6-4.html

[2] https://downloads.haskell.org/~ghc/6.6/docs/html/users_guide/release-6-6.html

查看更多
家丑人穷心不美
3楼-- · 2020-07-27 03:45

Okasaki in his book Purely Functional Data Structures, describes a FIFO queue as a pair of lists, front and back, where the front list contains the front elements of the queue in the correct order, and the back list contains the rear elements of the queue in the reverse order.

data Queue a = Queue [a] [a]  -- front & back lists

The idea is that new items are inserted to front of the back list, whereas values are popped out from the front list. If the front list becomes empty it is replaced by the reverse of the back list.

The queue maintains the invariance that the front list can be empty only if the back list is also empty; and performs amortized O(1).

-- helper function to maintain the invariance:
-- front list can be empty only if the back list is also empty
fill :: Queue a -> Queue a
fill (Queue [] b) = Queue (reverse b) []
fill q = q

push :: a -> Queue a -> Queue a
push x (Queue f b) = fill $ Queue f (x:b)

front :: Queue a -> Maybe a
front (Queue (x:_) _) = Just x
front _               = Nothing

pop :: Queue a -> Maybe (Queue a)
pop (Queue (_:xs) b) = Just . fill $ Queue xs b
pop _                = Nothing
查看更多
登录 后发表回答