I’m working on a small concept project in Haskell which requires a circular buffer. I’ve managed to create a buffer using arrays which has O(1) rotation, but of course requires O(N) for insertion/deletion. I’ve found an implementation using lists which appears to take O(1) for insertion and deletion, but since it maintains a left and right list, crossing a certain border when rotating will take O(N) time. In an imperative language, I could implement a doubly linked circular buffer with O(1) insertion, deletion, and rotation. I’m thinking this isn’t possible in a purely functional language like Haskell, but I’d love to know if I’m wrong.
I’m working on a small concept project in Haskell which requires a circular buffer.
Share
The
STmonad allows to describe and execute imperative algorithms in Haskell. You can useSTRefs for the mutable pointers of your doubly linked list.Self-contained algorithms described using
STare executed usingrunST. DifferentrunSTexecutions may not shareSTdata structures (STRef,STArray, ..).If the algorithm is not "self contained" and the data structure is required to be maintained with IO operations performed in between its uses, you can use
stToIOto access it in theIOmonad.Regarding whether this is purely functional or not – I guess it’s not?