Re: Graphics manipulation question [revision]
- To: mathgroup at smc.vnet.net
- Subject: [mg8444] Re: [mg8318] Graphics manipulation question [revision]
- From: Allan Hayes <hay at haystack.demon.co.uk>
- Date: Sat, 30 Aug 1997 00:42:55 -0400
- Sender: owner-wri-mathgroup at wolfram.com
Here is some simpler and faster code.
Please not that the function to be applied now comes first , as in
MapAt and the rest of the input is as for Cases.
MapAtCases::usage =
"MapAtCases[fn, expr, pattern]applies the function fn at each
part of expr that matches pattern.
\nMapAtCases[fn,expr, pattern,lev, k, opts], applies fn at up to k
positions in level lev.Default values are : for k, Infinity; for
lev,1. There is only one option, Heads ->Infinity.
(the arrangement and behaviour of the inputs apart from the first
one is like that of Cases).
\nThe data for fn for action at position pos are expr[[pos]],pos,
index (first, second ... selection made), k, total number of
selections made.";
Options[MapAtCases] = {Heads -> False};
MapAtCases[fn_,expr_,pat_,lev_:1,k_:Infinity, opts___?OptionQ] :=
Module[{n = 0, ln, pos},
pos = Position[expr, pat, lev, k, opts,
Sequence @@ Options[MapAtCases]];
ln = Length[pos];
MapAt[fn[#1, pos[[++n]], n, k, ln] & , expr, pos]
]
Examples
(1)
MapAtCases[f,{a,{a,b},a[b],a},a]
{f[a, {1}, 1, Infinity, 2], {a, b}, a[b],
f[a, {4}, 2, Infinity, 2]}
MapAtCases[f,{3,{3,2},3[2],3},3,{2}]
{3, {f[3, {2, 1}, 1, Infinity, 1], 2}, 3[2], 3}
MapAtCases[f,{a,{a,b},a[b],a},a,{2},2,Heads->True]
{a, {f[a, {2, 1}, 1, 2, 2], b}, f[a, {3, 0}, 2, 2, 2][b], a}
(2)
g = Graphics[Table[Circle[{Random[],Random[]}, Random[]],{10}]];
cl = Table[Hue[Random[]],{10}];
MapAtCases2[{cl[[#3]],#}&,g,Circle[_,_?(#<.7&)],
Infinity
];
Show[%, AspectRatio -> Automatic];
Note:
This form has been designed to ease the user's task by providing a
great deal of data for immediate use. In fact so long as we the
function f can access the index (first, third,
choice ..) and the list of positions then the user can do just as
much but with a little more programming:
In MapAtCases2, below, I have stored the positions in the variable
MACPostions - which would be in the package context if the function
were properly packaged and would need a usage message.
MapAtCases2[fn_,expr_,pat_,lev_:1,k_:Infinity,
opts___?OptionQ] :=
Module[{n = 0, ln},
MACPositions = Position[expr, pat, lev, k, opts,
Sequence @@ Options[MapAtCases]];
MapAt[fn[++n]& , expr, MACPositions]
]
gg ={a,{a,b},a[b],a};
MapAtCases2[f[gg[[MACPositions[[#]]]],#]&,gg,a]
{f[{a},1],{a,b},a[b],f[{a},2]}
MapAtCases2[{cl[[#]],
g[[Sequence@@MACPositions[[#]]]]}&,g,Circle[_,_?(#<.7&)],
Infinity
];
Show[%, AspectRatio -> Automatic];
Allan Hayes
hay at haystack.demon.co.uk
http://www.haystack.demon.co.uk/training.html
voice:+44 (0)116 2714198
fax: +44 (0)116 2718642
Leicester, UK