Browse thread
immutable Strings?
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Pascal Zimmer <Pascal.Zimmer@s...> |
| Subject: | Re: [Caml-list] immutable Strings? |
Oliver Bandel wrote: > for records it is possible to say "mutable" to change a normally > non mutable value into a mutable one. > > It would be nice to have the possibility to turn on > immutability fpr strings with a keyword like "immutable" > or so. > > So it could be forbidden to modify strings in cases, > where it makes sense; otherwise it must be provided > String.copy at a lot of cases in a program, that > want's to forbid modyfiing the original data. > > And disallowing a modification is much stronger/more strict > than only allowing modyfiing a copy. > So, it would be nice to have such a feature in newer versions > of OCaml. You can achieve the same effect quite easily using modules to provide a new interface to String, where you restrict the set of possible operations and abstract the datatype: module type IMMSTRING = sig type t (* abstract type *) val create : string -> t val copy : t -> t val copy_to_string : t -> string val get : t -> int -> char val cat : t -> t -> t val print_string : t -> unit (* ... *) end;; module ImmString : IMMSTRING = struct type t = string let create = String.copy let copy = String.copy let copy_to_string = String.copy let get s i = s.[i] let cat s t = s ^ t let print_string = print_string (* ... *) end;; Now you can write: # let s = ImmString.create "abcde";; val s : ImmString.t = <abstr> # ImmString.get s 0;; - : char = 'a' # s.[0] <- 'f';; This expression has type ImmString.t but is here used with type string The bad points: - you cannot use the shortcuts s.[i] and (^) anymore (this gets the code less readable especially for the first one) - you have to make a copy when creating an immutable string; if you were not planning to keep the original string to modify it, this copy is in fact useless Pascal