Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: [Caml-list] help
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: skaller <skaller@u...>
Subject: Re: [Caml-list] help
On Mon, 2004-04-26 at 02:30, mohammad siddiqui wrote:
> John,
> 
> I tried exactly what you have told. Its is fine when we just have one 
> element in an array of words. If we have more than one, changing the value 
> of one changes the values of the rest of the elements.

I suggest you first try a *purely functional* approach.
The reason is: its easier! It will work exactly as you expect,
no suprises .. I promise <g>.

Get rid of references and mutable fields. Forget efficiency
concerns at this time.

Here is how to make a doc, containing words, where i have
simplified the data structures to demonstrate:

type wrd = string
type doc = { id:int; words: wrd list }

let add_word d w= { d with words = w::d.words }

(* NOTE: functional update syntactic sugar saves 
explicitly copying each field .. unmentioned fields
get copied automatically *)

let empty = { id=99; words=[] }
let d = ref empty
;;

List.iter
(fun w -> d := add_word !d w)
["Hello";"This";"is";"a";"Document";"of";"words"]
;;

List.iter print_endline (!d.words)
;;


Note here i AM using a reference to hold the doc,
but the technique of adding a word to a doc
is purely functional: you get a brand new doc
for every word you add.

EXERCISE: use a fold to get rid of the 'd' variable,
making this little program *purely* functional
(up to the printing part anyhow :D

QUESTION: how fast is the functional technique
compared with using mutable fields or references
to modify a data structure in place??

I don't know the answer . but I'm going to GUESS.
The functional technique is 10% FASTER!

-- 
John Skaller, mailto:skaller@users.sf.net
voice: 061-2-9660-0850, 
snail: PO BOX 401 Glebe NSW 2037 Australia
Checkout the Felix programming language http://felix.sf.net



-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners