Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] function
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Oleg <oleg_inconnu@m...>
Subject: Re: [Caml-list] function
On Thursday 05 December 2002 05:00 am, Pierre Weis wrote:
> > On Mon, Dec 02, 2002 at 04:55:06PM +0100, altavillasalvatore@libero.it 
wrote:
> > > Hi all,
> > > I would want to know if a function exists that allows me to make this:
> > >
> > > ["123";"45";"678"]  ->  [1;2;3;4;5;6;7;8;].

[...]

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'));
}


(defun f (list)
  (loop for i in list nconcing
        (loop for j across i
              collect (- (char-int j) (char-int #\0)))))


let digit c = int_of_char c - int_of_char '0'

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 [])

If the input is a list of L strings of length S, then the complexity of all 
versions is O(L*S), assuming that "nconcing" caches the last element and
String.length is O(1).

Cheers
Oleg
-------------------
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