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 ocaml.org.

Browse thread
string -> charlist
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-05-08 (22:20)
From: Michel Quercia <michel.quercia@p...>
Subject: Re: "ocaml_beginners"::[] string -> charlist
Le Wed, 8 May 2002 22:52:34 +0200 (MET DST)
Oliver Bandel <oliver@f...> écrivit :

> Hello,
> 
> I got a problem,...
> let rec charlist_of_string str =
> let len = String.length str in
> if len = 0 then []
> else
> str.[0] :: charlist_of_string (String.sub str 1
> (len -1))
> 
> 
> 
> charlist_of_string "Hallo9z g g"

You forgot to end the definition of charlist_of_string with two
semicolons.

By the way, your code is inefficient because you ask Ocaml to copy the
string with one character less each time you put a character in the list.
You can avoid copying the string by giving an index in the string as
second argument. The following code does this, and builds the list from
right to left so as to be tail recursive :

let char_list_of_string str =
let rec job i res =
if i < 0 then res else job (i-1) (str.[i] :: res)
in job (String.length(str)-1) []
;;

Regards,
-- 
Michel Quercia
23 rue de Montchapet, 21000 Dijon
http://michel.quercia.free.fr (maths)
http://pauillac.inria.fr/~quercia (informatique)
mailto:michel.quercia@p...