Zulip Chat Archive

Stream: Is there code for X?

Topic: Merge (ordered) streams


Logan Murphy (Feb 02 2022 at 16:26):

Is there a way to use what's in data.stream to merge two ordered streams into an ordered stream? I'm guessing that if so, it uses stream.corec_on but I'm not quite sure how it would be done

Logan Murphy (Feb 02 2022 at 16:28):

E.g. merging

[0,1,2,4,6....]
[3,5,7...]

results in

[0,1,2,3,4,5,6....]

Alex J. Best (Feb 02 2022 at 17:27):

Here's a fun (monadic) way

def merge (a b : stream ) : stream  := corec_state ((do
    (c, d)  get,
    if c.head < d.head then
      put (c.tail,d) >>
      return c.head
    else
      put (c,d.tail) >>
      return d.head) : state (stream  × stream ) )
  (a, b)
#eval (merge ([0,1,2,4,6] ++ₛ(const 8))
             ([3,5,7] ++ₛ const 8)).take 10

Logan Murphy (Feb 02 2022 at 17:35):

Ah, interesting! Thanks for sharing, Alex

Yury G. Kudryashov (Feb 02 2022 at 17:40):

Note that streams are highly computationally ineffective.


Last updated: Dec 20 2023 at 11:08 UTC