If I'm counting the occurences of characters in a string, I could easily implement this using an array in an imperative language, such as the following:
char values[256]; char c;
while (c = readChar()) {
values[c] += 1;
}
I can see how to do this in Haskell using something like Data.Vector.Mutable, which provides fast implementation of int-indexed mutable arrays.
But how could I easily do this using just Haskell with no additional packages and/or extensions? Of in other words, how can I implement a fast O(1) collection with indexing and mutability?
The implementation of
vectoruses internal GHC functions called primops. You can find them in the packageghc-primwhich is hard-wired into GHC. It provides, among others, the following array functions:These functions are implemented by GHC itself, but they are really lowlevel. The
primitivepackage provides nicer wrappers of these functions. For arrays, these are:Here is a simple example using these functions directly (IO is a
PrimMonad):Of course, in practice you would just use the
vectorpackage, which is much more optimized (stream fusion, ...) and also easier to use.