Browse thread
recursion/iterator question
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Martin Jambon <martin_jambon@e...> |
| Subject: | Re: [Caml-list] recursion/iterator question |
On Sun, 16 Apr 2006, 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?
You can use list comprehensions.
See http://oandrieu.nerim.net/ocaml/#pa_compr
let triplets l = [+ (x, y, z)
| x <- l
| y <- l
| z <- l
| when x < y && y < z ];;
That's not optimal, but it's pretty clear.
> 2) is there a cleaner way to iterate over all triplets in a list?
You can do that, it should perform better:
let rec iter_full f = function
[] -> ()
| x :: l -> f x l; iter_full f l
let iter_tail iter f l = iter_full (fun x l -> iter (f x) l) l
let iter_full3 f l = iter_tail (iter_tail iter_full) f l
let iter3 f l = iter_full3 (fun x y z _ -> f x y z) l
Martin
--
Martin Jambon, PhD
http://martin.jambon.free.fr
Edit http://wikiomics.org, bioinformatics wiki