Browse thread
[Caml-list] Re: "ocaml_beginners"::[] string to list
-
Issac Trotts
-
Brian Hurt
-
Issac Trotts
- sebastien FURIC
-
Issac Trotts
- Issac Trotts
- Michal Moskal
-
Brian Hurt
[
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: | sebastien FURIC <sebastien.furic@t...> |
| Subject: | Re: [Caml-list] Re: "ocaml_beginners"::[] string to list |
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 = <fun>
> >># 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