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 (06:50) From: Li-Thiao-Té_Sébastien Subject: Re: [Caml-list] recursion/iterator question
```Tato Thetza wrote:
> 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?
> 2) is there a cleaner way to iterate over all triplets in a list?
>
Hi,

I suggest turning the list into an array, then using for-loops instead
of trying to explicitly generate the list of all possible triplets. If
you need to accumulate the results, you can use a list ref. This amounts
to implementing a set using an array instead of a list; unfortunately it
is not functional :(

let iterate f l =
let t = Array.of_list l in
let n = Array.length t in
let results = ref [] in
for i = 0 to n-1 do
for j = 0 to n-1 do
for k = 0 to n-1 do
results := f (t.(i),t.(j),t.(k)) :: results
done done done
;;

--
Li-Thiao-Té Sébastien

```