I am trying to use -->
operator with highest precedence
Unprotect[LongRightArrow];
LongRightArrow[obj_,property_]:=obj[ToString[property]];
Protect[LongRightArrow];
With this I can do basic operations like accessing properties of an association
In:= obj = <|"a" -> {2, 3}, "b" -> 5|>
Out:= <|"a" -> {2, 3}, "b" -> 5|>
In:= obj⟶a
Out:= {2, 3}
However when I try to access elements of list in obj-->a
Part
takes higher precedence. Same applies for operator ^
.
In:= obj⟶a[[1]]
Out:= Missing["KeyAbsent", "a[[1]]"]
In:= obj⟶a^2
Out:= Missing["KeyAbsent", "2 a"]
Answer
How about overloading the LongRightArrow
with a special rule for Part[...]
as the second argument?
Unprotect[LongRightArrow];
SetAttributes[LongRightArrow, HoldRest]
LongRightArrow[obj_, property_] := obj[ToString[property]];
LongRightArrow[obj_, Part[property_, partspec__]] :=
Part[LongRightArrow[obj, property], partspec];
Protect[LongRightArrow];
obj = <|"a" -> {2, 3}, "b" -> 5|>
obj⟶a
obj⟶a[[1]]
<|"a" -> {2, 3}, "b" -> 5|>
{2, 3}
2
Chip Hurst was quicker than I to show the generalization
LongRightArrow[obj_, head_[f_, args__]] := head[LongRightArrow[obj, f], args]
So I'll just take one more step to handle unary postfix operators, such as !
(Factorial
). Trivial by replacing args__
with args___
:
LongRightArrow[obj_, head_[f_, args___]] := head[LongRightArrow[obj, f], args]
Now
obj⟶a!
{2, 6}
EDIT
Re the comment:
obj⟶a⟶b
is equivalent to
LongRightArrow[obj, a, b]
while the desired behavior is
LongRightArrow[LongRightArrow[obj, a], b]
Well, obviously, that's exactly what we should tell Mathematica, it can't guess that for us.
LongRightArrow[obj_, a_, b__] := LongRightArrow[LongRightArrow[obj, a], b]
obj⟶a⟶b⟶b⟶b⟶b⟶b
(((((obj⟶a)⟶b)⟶b)⟶b)⟶b)⟶b
Comments
Post a Comment