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 (03:12) From: Jon Harrop Subject: Re: [Caml-list] recursion/iterator question
```On Sunday 16 April 2006 22:11, Tato Thetza wrote:
> Hi caml-list
> 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.
>
> questions:
> 1) what would be the best way to write triplets?

As 3-tuples, as you have done.

> 2) is there a cleaner way to iterate over all triplets in a list?

I think you mean _tabulate_ all triplets _from_ a list. You can write a
function to tabulate all pairs like this:

# let rec f2 = function
[] -> []
| a::t -> List.map (fun b -> a, b) t @ f2 t;;
val f2 : 'a list -> ('a * 'a) list = <fun>

and then another to tabulate all triplets like this:

# let rec f3 = function
[] -> []
| a::t -> List.map (fun (b, c) -> a, b, c) (f2 t) @ f3 t;;
val f3 : 'a list -> ('a * 'a * 'a) list = <fun>

On the example you gave:

# f3 [1;2;3;4];;
- : (int * int * int) list = [(1, 2, 3); (1, 2, 4); (1, 3, 4); (2, 3, 4)]

--
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
Objective CAML for Scientists
http://www.ffconsultancy.com/products/ocaml_for_scientists

```