Browse thread
[Caml-list] New to OCaml: can someone explain how this code can be done better?
- Jeremy Fincher
[
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: | 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) :: []
else
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))
done;
!l;;
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!
Thanks,
Jeremy
_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com
-------------------
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr