Re: Overloaded functions in Ocaml?
"Hendrik Boom [email protected] [ocaml_beginners]" <[email protected]> Thu, 3 Mar 2016 13:52:57 -0500
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <[email protected]> |
On Wed, Mar 02, 2016 at 11:17:34PM -0600, Douglas Lewit [email protected] [ocaml_beginners] wrote: > Although I don't understand why lists are called immutable in Ocaml or any > functional language. If a list is really an immutable or "frozen" object ( > borrowing a term from Ruby ) then it should be impossible to do this: > > 1 :: [2; 3; 4; 5] ;; > > Unless of course [1; 2; 3; 4; 5] and [2; 3; 4; 5] are two separate lists > with different memory addresses. ( And the old list gets garbage collected > since a variable name no longer references it? ) > > Sorry if these questions are a little elementary, but I'm still in the > learning stages. Because you can't change the contents of a list. You can only make a new one with different contents. That's what is happening in your example. You build a new list. But because OCaml can rely on [2; 3; 4; 5] not changing, it can save storage space by having th lists [1; 2; 3; 4; 5] and [2; 3; 4; 5] share storage. If you *could* change a list element, say, changing the 4 in [2; 3; 4; 5] to a 7, i.e., making it into [2; 3; 7; 5], it would have the side effect of changing the [1; 2; 3; 4; 5] you built above into a [1; 2; 3; 7; 5]. Which is probably not what you intended. To make this work in an intuitive way, all the list processing operations would have to do a lot of copying. Now there are languageas in which modifying lists it the normal way to do things. For some purposes this is significantly more efficient. But it is also quite error-prone. -- hendrik