From mboxrd@z Thu Jan 1 00:00:00 1970 Received: (from majordomo@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id JAA26713; Tue, 18 Feb 2003 09:21:55 +0100 (MET) X-Authentication-Warning: pauillac.inria.fr: majordomo set sender to owner-caml-list@pauillac.inria.fr using -f Received: from nez-perce.inria.fr (nez-perce.inria.fr [192.93.2.78]) by pauillac.inria.fr (8.7.6/8.7.3) with ESMTP id JAA26731 for ; Tue, 18 Feb 2003 09:21:54 +0100 (MET) Received: from mailhost.tni.fr (firewall.tni.fr [195.25.255.61]) by nez-perce.inria.fr (8.11.1/8.11.1) with ESMTP id h1I8LsP17194 for ; Tue, 18 Feb 2003 09:21:54 +0100 (MET) Received: from groscool.tni.fr ([195.25.255.1]) by mailhost.tni.fr (Netscape Messaging Server 3.62) with SMTP id 2146 for ; Tue, 18 Feb 2003 09:21:26 +0100 Received: from 192.168.7.60 by groscool.tni.fr (InterScan E-Mail VirusWall NT); Tue, 18 Feb 2003 09:21:25 +0100 (Paris, Madrid) Message-ID: <3E51EC82.6A09C8AD@tni.fr> Date: Tue, 18 Feb 2003 09:19:14 +0100 From: "sebastien FURIC" X-Mailer: Mozilla 4.78 [fr] (Windows NT 5.0; U) X-Accept-Language: fr MIME-Version: 1.0 To: OCaml List Subject: Re: [Caml-list] Re: "ocaml_beginners"::[] string to list References: <3E516E75.3030703@ucdavis.edu> Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit Sender: owner-caml-list@pauillac.inria.fr Precedence: bulk Issac Trotts a écrit : > > Brian Hurt wrote: > > >On Mon, 17 Feb 2003, Issac Trotts wrote: > > > > > > > >>Christian Schaller wrote: > >> > >> > >> > >>>Hi everyone! > >>> > >>>I'm trying to find a built in function for converting a string to a list of > >>>characters, similar to SML's explode. Is something like this available? > >>> > >>>Thank you! > >>> > >>>- Chris > >>> > >>> > >>> > >># let explode s = > >> let n = String.length s in > >> let rec aux k = if k = n then [] else s.[k] :: aux (k+1) in > >> aux 0;; > >> val explode : string -> char list = > >># explode "foo";; > >>- : char list = ['f'; 'o'; 'o'] > >> > >> > >> > > > >let explode s = > > let n = String.length s in > > let rec aux k accum = if k = n then (List.rev accum) > > else aux (k+1) (s.[k] :: accum) > > in > > aux 0 [] > >;; > > > >See previous discussion. > > > Good point: we want it to be tail-recursive. > Just to clean up, and make it more efficient... > > let explode s = > let rec aux k accum = if k = -1 then accum > else aux (k-1) (s.[k] :: accum) > in > aux (String.length s - 1) [] > ;; Sometimes the imperative version seems more clear: let explode s = let res = ref [] in for i = String.length s - 1 downto 0 do res := s.[i] :: !res done; !res Sébastien. ------------------- 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