Subj : Re: any function to handle this kind of counting? To : comp.programming From : Jon Harrop Date : Fri Jul 29 2005 07:31 pm Ross wrote: > and then i want to count, say, for "1", there are two A's, one E, ... > > it seems that a for loop can do the job but as we don't know how many > instances there are, i.e. don't know A, C, E and then what will occur in > this corresponding vector, is there any function which is devoted to > handle this kind of counting problem? thx!! You can do this quite simply in OCaml: # let a = [ 1; 3; 2; 1; 1; 3; 2; 1 ] in let b = ['A';'A';'A';'A';'C';'C';'E';'E'] in let ab = List.combine a b in let rec add b = function [] -> [b, 1] | (b', n) :: t when b=b' -> (b', n+1) :: t | h :: t -> h :: add b t in let rec add2 (a, b) = function [] -> [a, [b, 1]] | (a', l) :: t when a=a' -> (a, add b l) :: t | h :: t -> h :: add2 (a, b) t in List.fold_right add2 ab [];; - : (int * (char * int) list) list = [(1, [('E', 1); ('C', 1); ('A', 2)]); (2, [('E', 1); ('A', 1)]); (3, [('C', 1); ('A', 1)])] The result indicates that for 1 there are 2 As, 1 C and 1 E, for 2 there is 1 E and 1 A and for 3 there is 1 C and 1 A. Basically: The "add" function increments the counter of the given char, or adds a new counter (initialised to 1) if none already exists. The "add2" function updates the counter of the given int * char pair, or adds a new counter (initialised to a -> 1b) if none already exists. The "fold_right" then accumulates the result by applying the "add2" function over each element in hte list of pairs "ab". This program is very simple to write in OCaml because the result is most easily built up in a linked list, which OCaml provides native support for. -- Dr Jon D Harrop, Flying Frog Consultancy http://www.ffconsultancy.com .