Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Newbie list question
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2009-05-15 (13:49)
From: Florian Hars <hars@b...>
Subject: Re: [Caml-list] Newbie list question
Joel Christner schrieb:
> What I'm wanting to do is create a ref list that contains a series of
> strings

Judging from your code, you really do not want to do this (I just sped up
a program of mine by at least two orders of magnitude fixing an error like
that). What you probably want to do is

module S = Set.Make(String);;

let s = ref S.empty;;

let add_variable_ref s v = 
  s := S.add v !s;;

add_variable_ref s "foo";;
add_variable_ref s "bar";;
S.elements !s;;

Even better if you can structure your code to get rid of the ref:

# let add_variable s v = S.add v s;;
val add_variable : S.t -> S.elt -> S.t = <fun>
# let vars = List.fold_left add_variable S.empty ["Foo"; "Bar"; "Baz"; "Foo"; "Qux"; "Baz"];;
val vars : S.t = <abstr>
# S.elements vars;;
- : S.elt list = ["Bar"; "Baz"; "Foo"; "Qux"]

Of course, this works as well, but uses more stack space as right folds are
not tail recursive:

# let vars' = List.fold_right S.add ["Foo"; "Bar"; "Baz"; "Foo"; "Qux"; "Baz"] S.empty;;
val vars' : S.t = <abstr>
# S.elements vars';;
- : S.elt list = ["Bar"; "Baz"; "Foo"; "Qux"]

-- Florian.