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: | 2006-04-17 (09:35) |
From: | Christian Stork <cstork@i...> |
Subject: | Re: [Caml-list] recursion/iterator question |
On Mon, Apr 17, 2006 at 01:06:22AM +0100, Jon Harrop wrote: > 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)" Just in case you didn't know, you're looking for an enumeration of all "3-sets" or "combinations" out of the set X. See for example http://mathworld.wolfram.com/Combination.html . > > 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. Or, if you choose to represent triplets as lists of three elements, you can generalize Jon's solution to let rec combs = function | (0, _) -> [[]] | (n, es) when n > List.length es -> [] | (n, e::es) -> List.map (fun l -> e::l) (combs (n-1, es)) @ combs (n, es) let triplets es = combs (3, es) Question to the rest of the list: The ocaml compiler complains with ... Warning P: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: (1, []) (However, some guarded clause may match this value.) ... Am I right to assume there's no way to get rid of this warning short of disabling P-warnings on the command line? (I can't list all the lacking patterns since they depend on n, right?) -- Chris Stork <> Support eff.org! <> http://www.ics.uci.edu/~cstork/ OpenPGP fingerprint: B08B 602C C806 C492 D069 021E 41F3 8C8D 50F9 CA2F