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

recursion/iterator question
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2006-04-17 (13:09) From: Xavier Leroy Subject: Re: [Caml-list] recursion/iterator question
> Given a list, I would like to iterate over all triplets in the list. For
> example, in mathematcs, its not uncommon to have expressions such as
> "for all i,j,k in set X, do f(i,j,k)"
>
> The only way I can think of is to create a list with all triplets of the
> list, so:
>   triplets([1,2,3,4]) = [(1,2,3),(1,2,4),(1,3,4),(2,3,4)]
> and take this list and map a function f to it.

Folds are more general than maps and tend to compose better.
Consider:

let list_fold_right_3 f l1 l2 l3 =
List.fold_right
(fun x1 -> List.fold_right (fun x2 -> List.fold_right (f x1 x2) l3) l2)
l1

Examples:

# list_fold_right_3 (fun x y z a -> (x,y,z)::a) [1;2] [3;4] [5;6] [];;
- : (int * int * int) list =
[(1, 3, 5); (1, 3, 6); (1, 4, 5); (1, 4, 6); (2, 3, 5); (2, 3, 6); (2,
4, 5);
(2, 4, 6)]
# list_fold_right_3 (fun x y z a -> (x+y+z)::a) [1;2] [3;4] [5;6] [];;
- : int list = [9; 10; 10; 11; 10; 11; 11; 12]
# list_fold_right_3 (fun x y z a -> x*y*z + a) [1;2] [3;4] [5;6] 0;;
- : int = 231

But, yes, if you find yourself doing this often, it's a good idea to
use the syntax extension for list comprehensions.

- Xavier Leroy