Message Boards Message Boards

2 Replies
5 Total Likes
View groups...
Share this post:

#[[1]]//FullForm equals 1?

Posted 12 years ago
I have a set of symbolic algebraic expressions that I'm trying to get some speed into. To illustrate the issue, I'll use a simple form like { k0 X, k1 Y, k1 Z}, where each term is large and complicated. By random walk, I've arrived at a promising form 

{ r0 X, r1 Y,r1 Z}/.r0->k0 /.r1->k1

which is faster than the original, but with my particular set of expressions, it turns out that a function is faster:

{#[[1]] X, #[[2]] Y, #[[2]] Z}&@@{k0, k1}

The expressions are large, making substitutions by hand time consuming and error prone, so I set out to replace the k s with a rule like


I was surprised that this wasn't a straightforward operation, k0 being replaced by 1 instead of the intended #[[1]]. I thrashed around for a bit, eventually finding the odd (to me) result that

{#[[1]], #[[2]]}//FullForm


List[ 1, Part[Slot[1],2]]

Can anyone suggest a way of thinking in which this makes sense? Is there any place in the design for Part[Slot[1],1] ? I worked around it with a hack:

{#[[2]] X, #[[3]] Y, #[[3]] Z}&@@{Null, k0, k1}

which works but is ugly to say nothing of embarrassing.
POSTED BY: Fred Klingener
2 Replies
# is Slot[1] so its first part is 1. Its second part, that is #[[2]], does not exist. I do not understand the nature of the replacement rules but something similar to this could be what you are looking for.

In[1]:= ((Evaluate[({r0 X, r1 Y, r1 Z} /. r0 -> k0 /.r1 -> k1) /. {k0 -> #1, k1 -> #2}]) &)
Out[1]= {X #1, Y #2, Z #2} &

In[2]:= ((Evaluate[({r0 X, r1 Y, r1 Z} /. r0 -> k0 /.r1 -> k1) /. {k0 -> #1, k1 -> #2}]) &) @@ {k0, k1}
Out[2]= {k0 X, k1 Y, k1 Z}

You can create the replacement list like this if you want

In[3]:= Thread[{k0, k1} -> Array[Slot, 2]]
Out[3]= {k0 -> #1, k1 -> #2}
Mathematica is a symbolic language.  Part[Slot[1], 1] is 1 just as Part[List[1], 1] is 1.  In particular, Slot[1] is not AtomQ, so taking its parts makes sense.
I'm not sure I understand for what you want the replacement rule, but the usual way to avoid premature evalution of the right-hand side of rules is to use RuleDelayed instead:
    {k0 :> #[[1]], k1 :> #[[2]]}
I'm also confused by your example,
{#[[1]] X, #[[2]] Y, #[[2]] Z}&@@{k0, k1}
for which I get a bunch of Part messages.  Did you mean
In[119]:= {#1 X, #2 Y, #2 Z} & @@ {k0, k1}
Out[119]= {k0 X, k1 Y, k1 Z}
which also avoids Part?
POSTED BY: Jeremy Michelson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract