typeclasses / haskell-phrasebook

The Haskell Phrasebook: a quick intro to Haskell via small annotated example programs
https://typeclasses.com/phrasebook
210 stars 22 forks source link

Add examples for mutable vectors #33

Closed cideM closed 1 year ago

cideM commented 4 years ago

This is an example for #6

As outlined in the issue I first go through a couple of commonly used functions from Data.Vector.Mutable, showing how to create, read and write MVs (including how to create them from an immutable vector).

Since it's hard to really separate MV from just V I also wanted to show that Data.Vector.modify can actually update an immutable vector in place.

Last but not least I included some lines to show that MV works with IO and also ST. This is a bit more advanced, but I think it's still important to know. MV isn't something you often reach for (I used it once to speed up an Advent of Code puzzle). So often you'll start with just a vector and then later on add mutability for speed. In those cases it can be really nice knowing that you can perform some mutations in a separate functions that just takes a plain old vector and gives you a plain old vector back. No IO spreading through your code.

The current example simple shows how to create an immutable vector, write to it, but then return an immutable, frozen vector from it. I could modify it to show the "take vec, mutate, return vec" but that's adding some more complexity to it of course.