MathGroup Archive 2000

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Newbie question: pairswise function application

on 6/12/00 2:17 PM, Sidney Cadot at sidney at wrote:

> Hi,
> Wandering through the 1500-odd pages of the Mathematica book, I can't
> find the solution to the following rather silly problem:
> I have a list L consisting of (a lot of) integers, and I want to apply a
> function f to all pairs of numbers; furthermore, I don't want to
> calculate both f[a,b] and f[b,a]:
> L = {1,5,19,100};
> ... and I want:
> { f[1,5], f[1,19], f[1,100], f[5,19], f[5,100], f[19,100] }
> Can anyone please tell me how to do this? I'd prefer a smart solution
> (i.e., not just generating all pairs, then throwing away a lot of them)
> since my lists tend to get rather large.
> Thanks in advance,
> Sidney Cadot
> sidney at
There is already such a faunction in the package
DiscreteMath`Combinatorica`. It is called KSubsets:

<< DiscreteMath`Combinatorica`

f @@@ KSubsets[{1, 5, 19, 100}, 2]

{f[1, 5], f[1, 19], f[1, 100], f[5, 19], f[5, 100], f[19, 100]}

I do not know how fast this is (functions in this package tend to be not
teribly fast since it has not been significantly updated for a long time)
but it uses backtracking so it should do better than making a list of all
pairs and throwing away some. There is actually a vast number of ways to
program something like this. I shall not try to consider efficiency (there
are regular contributors to this list who know a lot more about this aspect
than me and I expect some of them will contribute their versions) but
instead give an example of the kind of Mathematica programming style which
is the reason why I think Mathematica is such a fantastic programming
language for a mathematician:

 L = {1, 5, 19, 100};
myfunction[i_, j_] /; i >= j := Sequence[];
myfunction[i_, j_] /; i < j := f[i, j]
Distribute[myfunction[L, L], List]
{f[1, 5], f[1, 19], f[1, 100], f[5, 19], f[5, 100], f[19, 100]}

Andrzej Kozlowski
Toyama International University, JAPAN

For Mathematica related links and resources try:

  • Prev by Date: Re: Rocket science!
  • Next by Date: System of lorenz equations
  • Previous by thread: Re: Newbie question: pairswise function application
  • Next by thread: Re: Newbie question: pairswise function application