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
[Caml-list] New to OCaml: can someone explain how this code can be done better?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2001-06-23 (05:27)
From: Jeremy Fincher <tweedgeezer@h...>
Subject: [Caml-list] New to OCaml: can someone explain how this code can be done better?
Since I'm learning OCaml, I've been writing little functions as I get a 
grasp on each little bit of the syntax.  One of these functions is 
"permute", which takes a string and returns a list of all the permutations 
of the string.  Here's the function:

let rec permute_rec f s =
  if String.length s = 1 then
    (f ^ s) :: []
    let l = ref [] in
    for i = 0 to ((String.length s) - 1) do
      let c = String.sub s i 1 in
      let rem = (String.sub s 0 i) ^ ((String.sub s (i+1) ((String.length 
s)-i-1))) in
	l := (List.append !l (permute_rec (f^c) rem))

let permute = permute_rec "";;

Now, I'm sure this isn't the best way to code that function.  What I'm 
hoping is that someone can show me a few things about the function: how to 
make it tail recursive; a better (less imperative?) method of writing it, 
and which parts are not consistent with common/standard OCaml idiom.  
*Anything* I'm shown should at least help me learn, so if you have any 
comments/opinions, please tell me!

Get your FREE download of MSN Explorer at

Bug reports:  FAQ:
To unsubscribe, mail  Archives: