David
David

Reputation: 3046

Why does ocaml have mutable arrays?

Why does Ocaml have mutable arrays? As far as i understood functional programming, it is to minimize side effects. Are mutable (edit:) Arrays not contrary to that thought?

Even strings are mutable in Ocaml, which is not even the case in python or is OCaml not considered to be a pure functional language?

Upvotes: 2

Views: 1758

Answers (2)

Goswin von Brederlow
Goswin von Brederlow

Reputation: 12332

Yes, mutable arrays are contrary to pure functional programming. But ocaml is far more than just functional programming. It has a lot of imperative and object oriented features as well.

In contrast to other data types, arrays have one main feature that sets them appart: random access (also named direct access) in constant time. And this includes both reading and writing. Without mutable arrays it would be impossible to have data structures with random access writes in constant time. This is essential for e.g. hash tables or heaps.

Now it could have been nice to have immutable arrays and mutable arrays and one can implement that easily with phantom types in such a way that a function expecting an immutable array will also accept a mutable array but not the other way around.

But the ocaml core language has historically grown to include everything needed for the ocaml interpreter/compiler and little else. There wasn't a need to have immutable arrays but need for mutable ones. So a straight forward mutable array type was implemented. It's easy to extend it to mutable/immutable arrays but that's left to extensions to the standard library.

Note: tuple are kind of immutable arrays. But they have a compile time fixed size and no index operator.

Note2: ocaml started with mutable strings. After many many years and still recently this was changed to Bytes (mutable) and String (immutable). Saddly not with phantom types so they aren't interchangable.

Upvotes: 3

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66803

OCaml is not a pure functional language, true. It has a pure functional subset, but supports mutation and many imperative constructs (as well as mutable OO objects). IMHO the point is to allow programmers to make the necessary tradeoffs while providing excellent support (and a kind of encouragement) to functional programming.

As @AnuragSoni points out, lists and arrays are different things in OCaml. Arrays are mutable but lists are not.

In my opinion, purely functional arrays are quite problematic. In my (modest) experience they aren't widely used in Haskell, for example. They are pure, yes, but not effective enough for many purposes.

Upvotes: 6

Related Questions