This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

[Caml-list] function
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2002-12-05 (21:04) From: Pal-Kristian Engstad Subject: Re: [Caml-list] function
```On Thursday 05 December 2002 12:46 pm, Oleg wrote:
> To help the original poster earn extra credit, I'll write the function in
> the three languages I [sort of] know:
>
> typedef std::list<char*> LS;
> typedef std::list<int> LI;
>
> void f(LS& input, LI& output) {
>     for(LS::iterator i = input.begin(); i != input.end(); ++i)
>         for(char* p = *i; *p != '\0'; ++p)
>             output.push_back(int(*p) - int('0'));
> }

Isn't there a foreach() algorithm in STL?

> let rec f_aux lst i acc =
>     match lst with
>
>     | [] -> acc
>     | x :: y when i = String.length x -> f_aux y 0 acc
>     | x :: y -> f_aux lst (i + 1) (digit x.[i] :: acc)
>
> let f lst = List.rev (f_aux lst 0 [])

Ah, the use of List.rev... :-) Of course, without it, it is hard. Here's my two
attempts:

let f4 strs =
let to_ord c = int_of_char c - int_of_char '0' in
let rec strings_to_list = function
| [] -> []
| str :: strs ->
let rec to_list s k n =
if k = n then strings_to_list strs else to_ord s.[k] :: to_list s (k + 1) n
in
to_list str 0 (String.length str)
in
strings_to_list strs

This one is unfortunately not tail recursive, but it is neat in the sense that it doesn't
use any library function except int_of_char.

let f5 strs =
let to_ord c = int_of_char c - int_of_char '0' in
let rec strings_to_list acc = function
| [] -> acc
| str :: strs ->
let rec to_list acc s k n =
if k = n then strings_to_list acc strs else to_list (to_ord s.[k] :: acc) s (k + 1) n
in
to_list acc str 0 (String.length str)
in
List.rev(strings_to_list [] strs)

Equivalent to Oleg's I believe?

PKE.
--
_
\`.       Pål-Kristian Engstad, Senior Software Engineer,
\ `|     Naughty Dog, Inc., 1315 3rd Street Promenade,
__\ |`.   Santa Monica, CA 90046, USA. (310) 752-1000 x799.