MathGroup Archive 1995

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

Search the Archive

how can I do this functionally?

  • To: mathgroup at christensen.cybernetics.net
  • Subject: [mg913] how can I do this functionally?
  • From: drc at gate.net (David Cabana)
  • Date: Sun, 30 Apr 1995 03:47:38 -0400

Below I define a function, Classify[S_, f_], in an imperative (and
not particularly efficient) style.  Can anyone tell me how to define 
it either functionally or via pattern matching?

The function Classify takes 2 arguments, f and S.  f is a function,
and S is a subset of the domain of S.  In particular, S is a list
of elements of the domain of f, and contains no repeated elements.

The function f induces an equivalence relation on S as follows:
a is equivalent to b modulo f if and only if f[a] == f[b]. Classify
returns the equivalence classes of S modulo f. 

In[1]:=
Classify[S_, f_]:=
Module[
   {values, partition, len, index},
   len = Length[S];
   partition = Table[{}, {len}];
   values = Map[f,S];
   
   Do[
      index = First[Flatten[Position[values, values[[i]]]]];
      partition[[index]] = Prepend[partition[[index]], S[[i]]],
      {i, 1, len}
   ];
   
   (* remove any empty lists from partition *)
   Select[partition, (#!={})&]
]

Here are some examples:

In[2]:= Classify[{-1,-2,1,2,3,4,5}, Positive]
Out[2]= {{-2, -1}, {5, 4, 3, 2, 1}}

In[3]:= Classify[{-1,-2,1,2,3,4,5}, EvenQ]
Out[3]= {{5, 3, 1, -1}, {4, 2, -2}} 

In[4]:= square[x_]:= x x

In[5]:=Classify[{-1,-2,1,2,3,4,5}, square]
Out[5]={{1, -1}, {2, -2}, {3}, {4}, {5}} 

In[6]:= cube[x_] := x x x

In[7]:= Classify[{-1,-2,1,2,3,4,5}, cube]
Out[7]= {{-1}, {-2}, {1}, {2}, {3}, {4}, {5}}

David Cabana  drc at gate.net   


  • Prev by Date: Re: How use the Union function (MMA v.2,2 on PC )?
  • Next by Date: how can I do this in functional style?
  • Previous by thread: Re: Eigensystem
  • Next by thread: how can I do this in functional style?