Re: Getting stuck with finding an elegant solution without global variables
- To: mathgroup at smc.vnet.net
- Subject: [mg124821] Re: Getting stuck with finding an elegant solution without global variables
- From: "Oleksandr Rasputinov" <oleksandr_rasputinov at ymail.com>
- Date: Wed, 8 Feb 2012 05:31:10 -0500 (EST)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
On Tue, 07 Feb 2012 09:08:28 -0000, Fredob <fredrik.doberl at gmail.com>
wrote:
> Hi,
>
> I am trying to find an elegant solution, i.e. without a global
> variable to the following problem:
>
> Given a list, e.g. {1,2,3,4}, create a new list where each element is
> a function of the "i th" element and the rest of the list, e.g.
>
> Branch[Elem_, List_] := Elem + Cases[List, Except[Elem]]
>
> The the result would be {{3, 4, 5}, {3, 5, 6}, {4, 5, 7}, {5, 6, 7}}
>
> I have used Map[f, List] but then I have to use a global variable in f
> to access the list itself, e.g. BranchG[Elem_] := Elem + Cases[List,
> Except[Elem]]
>
It seems to me that you are asking not for elegant solutions per se, but
rather for solutions in a pure functional style. As such I assume that it
is not so much global variables that you wish to avoid using as any
user-defined named symbols (variables) at all. Actually, the clearest way
to accomplish this (in my opinion) is indeed to use Map:
Function[{f, lst},
Through[f[Part, Delete][lst, #]] & /@ Range@Length[lst]
][Plus, {1, 2, 3, 4}]
{{3, 4, 5}, {3, 5, 6}, {4, 5, 7}, {5, 6, 7}}
Obviously other functions can be used as well, such as Times:
Function[{f, lst},
Through[f[Part, Delete][lst, #]] & /@ Range@Length[lst]
][Times, {1, 2, 3, 4}]
{{2, 3, 4}, {2, 6, 8}, {3, 6, 12}, {4, 8, 12}}
Or we can return a closure over the list, leaving f unspecified until
later:
In :=
Function[lst,
Function[f,
Through[f[Part, Delete][lst, #]] & /@ Range@Length[lst] // Evaluate
]
][{1, 2, 3, 4}]
Out =
Function[f$,
{f$[1, {2, 3, 4}], f$[2, {1, 3, 4}],
f$[3, {1, 2, 4}], f$[4, {1, 2, 3}]}
]
In :=
%[Plus]
Out =
{{3, 4, 5}, {3, 5, 6}, {4, 5, 7}, {5, 6, 7}}
And just for fun here is one without Map:
Function[{f, lst},
Range@Length[lst] // Function[idx,
Through[f[Part, Delete][lst, idx]],
Listable
]
][Plus, {1, 2, 3, 4}]
{{3, 4, 5}, {3, 5, 6}, {4, 5, 7}, {5, 6, 7}}
Although it is not so important here as we have not employed any
user-defined symbols in the above, I would caution you against using
symbol names starting with capital letters. Especially names like List,
which are already in use for fundamental Mathematica language constructs.