4

Several functions work with symbols in MMA: Take for example Part:

l1=l2=Range[4];
l1[[3]]
(*3*)
l2[[4]]
(*4*)

I want to make my own function work in the same way.

I can do some thing like this:

p[l_,x_]:=l[[x]]
p[l1,3]
(*3*)
p[l2,4]
(*4*)

Now I want to use a symbol for example assign [[[]]]] or [*@] (or any other symbol) to my p function so that I can do something like this:

l1[[[3]]]
(*3*)
l2[[[4]]]
(*4*)

or

l1[*@3]
(*3*)
l2[*@4]
(*4*)
Sjoerd C. de Vries
  • 65,815
  • 14
  • 188
  • 323
Basheer Algohi
  • 19,917
  • 1
  • 31
  • 78

3 Answers3

6

I'll give you a simple example of one operator without built-in meaning that I have re-purposed.

I recently found myself plotting functions or evaluating integrals on a square domain centered on the origin that could be represented by Rectangle[{-a, -a}, {a, a}]. Tired of typing in the Rectangle expression, I noticed that there is a Square expression and operator (esc+sq+esc, $\square$) that is defined but has no meaning, so I assigned it one as follows:

Clear[Square]
Square[x_ /; x > 0] := Rectangle[{-x, -x}, {x, x}]

I can now write expressions like the following:

ContourPlot[Cos[(x^2 - y^2)/3], {x, y} \[Element] \[Square](2 Pi), PlotPoints -> 50]

which will look like this in the notebook:

ContourPlot expression

ContourPlot output

... or like the following:

Integrate[Cos[(x^2 - y^2)/3], {x, y} \[Element] \[Square]3]

which will look like this:

integral expression

integral output

MarcoB
  • 67,153
  • 18
  • 91
  • 189
4

This solution doesn't provide quite the flexibility that you've given as an example but may still be satisfactory:

Have a look at: https://reference.wolfram.com/language/tutorial/OperatorsWithoutBuiltInMeanings.html and How to define custom operators

That'll allow you to assign a function to an unused (or used) in-fix operator. Operator precedence may be important to consider if you do this (https://reference.wolfram.com/language/tutorial/OperatorInputForms.html). I don't remember if you can / how to redefine operator preference to suit your needs.

Ian
  • 81
  • 1
2
l1 = l2 = Range[4];
p[l_, x_] := l[[x]]

This is a example of MakeExpression. You might need to make a new expression like this.

MakeExpression[RowBox[{l_, "[", 
      RowBox[{"[", RowBox[{"[", x_, "]"}], "]"}], "]"}], StandardForm] := 
 MakeExpression[RowBox[{"p", "[",RowBox[{l, ",", x}], "]"}], StandardForm]

l1[[[3]]]
(*3*)

And other example.

MakeExpression[RowBox[{l_, "[", 
      RowBox[{"*", RowBox[{"@", x_}]}], "]"}], StandardForm] := 
 MakeExpression[RowBox[{"p", "[", RowBox[{l, ",", x}], "]"}], StandardForm]

l1[*@3]
(*3*)
Junho Lee
  • 5,155
  • 1
  • 15
  • 33