Re: how can I do this functionally?
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg939] Re: how can I do this functionally?
- From: tomi (Tom Issaevitch)
- Date: Wed, 3 May 1995 00:18:23 -0400
- Organization: Wolfram Research, Inc.
drc at gate.net (David Cabana) writes: >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 You can use Union and select: In[195]:= Classify[s_, f_]:= With[{v = Union[Map[f, s]]}, Map[Select[s, Function[{z}, f[z] == #]]&, v]] In[196]:= Classify[{-1,-2,1,2,3,4,5}, Positive] Out[196]= {{-1, -2}, {1, 2, 3, 4, 5}} In[197]:= Classify[{-1,-2,1,2,3,4,5}, #^2&] Out[197]= {{-1, 1}, {-2, 2}, {3}, {4}, {5}} Tom Wolfram Research