Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

V10 introduces an operator form for several functions perhaps primarily due to their role in queries as part of introducing data science functionality. At first pass it seems a lot of effort to add some syntactic sugar (given an equivalent pure functional form only ever requires an extra couple of symbols - (#, &) )? For example,Map[f,#]&[{a,b,c}]can now be shortened to Map[f][{a,b,c}], - slightly more compact but then again perhaps not such an improvement on an existing operator (short) form - f/@{a,b,c}.

So, are there some compelling examples that illustrate the rationale behind the introduction of this new construct?

Conclusion

To summarize the points made in all the informative responses:

  • In addition to avoiding the symbols ((#&)) operator forms can eliminate the need for Function in nested definitions.
  • The gains of using operator form are cumulative as they are chained together either in postfix, prefix or for some, infix form.
  • While not necessarily restricted to this area the motivation and applicability of operator forms stems from the need to provide functions as arguments in Dataset.
  • Many operator forms are built-in but when not they can be readily defined.
  • The pure and operator forms are not always semantically equivalent (natively or user-defined) with, for example, Query using their different patterns to interpret differently.
  • They can potentially be used to improve efficiency not just via code's reduced leaf-count but in reduced algorithmic complexity.
  • They are potentially a rich source of language improvement from mimicking natural language patterns, code refactoring, debugging or automated and non-deterministic parsing via corpus-derived context.
share|improve this question
    
not Map[f]{a,b,c} but Map[f][{a,b,c}]. –  Wouter Aug 3 at 11:51
    
Corrected. Thanks. –  Ronald Monson Aug 3 at 13:20
1  
I find them indispensable when exploring any kind of data, since you can just keep tacking things like // Map[..#..&] or //Select[..#..&] onto the end of expressions. –  jtbandes Aug 3 at 18:21
1  
I am so glad to see people coming to the same conclusions that I did about operator forms! –  Taliesin Beynon Aug 7 at 18:11
1  
@TaliesinBeynon, why not operator form for everything --> Mod[11], ListPlot[Joined->True], Translate[{0,1}], StringSplit[{"..."}] –  alancalvitti Sep 7 at 18:29

5 Answers 5

up vote 18 down vote accepted

I would have liked to have more experience with the operator forms before this question was asked as I am short on examples, and I'm sure my opinion will evolve over time. Nevertheless I think I have enough familiarity with similar syntax to provide some useful comments.

Taliesin Beynon provided some background for this functionality in Chat:

Operator forms have turned out to be a huge win for writing readable code. Unfortunately I can't remember whether it was Stephen or me who first suggested them, so I don't know who should get the credit :). Either way it was a major (and risky) decision, and I had to argue with a lot of people in the company who remained skeptical, so credit goes to Stephen for just pushing it through. But they were motivated by the needs of Dataset's query language, which is an interesting historical detail I think.

We see that m_goldberg is correct in seeing operator forms as being important to Dataset.

Taliesin also claims that operator forms are "a huge win" for readability. I agree with this and have been a proponent of SubValues definitions, which is basically what "operator forms" are. I also like Currying(1),(2) though I haven't embraced it to the same degree.

You comment that operator forms only save a few characters over anonymous functions and this is usually true, but these characters, and more importantly the semantics behind them, are nevertheless significant. Being able to treat functions with partially specified parameters as functions (Currying) frees us from the cruft or baggage of a lot of Slot and Function use. Surely these are easier to read and write:

fn[1] /@ list                   (*  fn[1, #] & /@ list             *)

SortBy[list, Extract @ 2]       (*  SortBy[list, Extract[#, 2] &]  *)

Note that I did not choose to use the operator form of SortBy here.

Since Mathematica uses a generally functional language these kinds of operations are frequent, which mean that these effects quickly compound. Code that contains multiple Slot Functions can be quite hard to read as it is not always clear which # belongs to which &. As a hurriedly contrived example consider this snippet:

(SortBy[#, Mod[#, 5] &] &) /@ (Append[#, 11] &) /@ Partition[Range@9, 3]

If we first provide "operators forms" for functions that do not presently have them:

partition[n_][x_] := Partition[x, n]
mod[n_][m_] := Mod[m, n]

Then write the line above using such forms in all applicable places:

SortBy[mod @ 5] /@ Append[11] /@ partition[3] @ Range @ 9

This is a considerable streamlining of syntax and much easier to read.

The example above is also semantically simpler:

Unevaluated[(SortBy[#1, Mod[#1, 5] &] &) /@ (Append[#1, 11] &) /@ 
    Partition[Range[9], 3]] // LeafCount

Unevaluated[SortBy[mod @ 5] /@ Append[11] /@ partition[3] @ Range @ 9] // LeafCount
20

11

Theoretically that could pay dividends in performance though I am uncertain of the present reality of this. Some operations are slower, possibly due to an inability to compile, while others are faster. However I believe that this simplification opens the door for future optimizations.

share|improve this answer
1  
Two useful takeaways here: Firstly, the extra brevity from avoiding (#&) is only part of the story. Operator forms also remove the need for Function usage for nested pure functions but further, even this doesn't seem to capture the advantages since when it comes to readability and conceptualisation it really does seem to be a case of the "whole being greater than the sum of the parts". Secondly, even when an operator form is not built in, one can readily be defined if warranted by the code. –  Ronald Monson Aug 4 at 13:22
    
This last point -defining your own operator form if needs be - is touched upon in the documentation (e.g. via the matches definition in the "titanic neat example") although perhaps it would have been worth emphasising a little more given its role in building up more powerful queries. It also relates to my speculation about these forms being automatically detectable given that most functions have a natural "data argument" (and/or other arguments can be inferred from the context). It also raises the spectre of wholesale code refactoring for improving the maintainability of legacy codebases. –  Ronald Monson Aug 4 at 13:37

For me the operator forms of Map and Apply will probably provide the most important benefits in terms of code readability. Often I need to apply a sequence of transformations to some data, and I am fond of infix notation for this purpose. For example I find

a ~Position~ 0 ~SortBy~ Last

more readable than the "conventional"

SortBy[Position[a, 0], Last]

because I do not have to scan backwards and forwards in the expression to match the SortBy with the Last.

This is only possible when using functions which take the data as their first argument. Because Map and Apply take the data as their second argument, they do not fit easily into the left-to-right infix syntax. If my final step is to map Max across the list I would need to use something like

a ~Position~ 0 ~SortBy~ Last ~(#2 /@ #1 &)~ Max

(if I was determined to stick with infix), or more likely

a ~Position~ 0 ~SortBy~ Last // Max /@ # &

In both cases I am having to use a pure function just to get the arguments of Map in the correct order. In practice I would probably abandon the left-to-right principle and put the last operation at the beginning of the expression:

Max /@ (a ~Position~ 0 ~SortBy~ Last )

The operator form means that I can chain the transformations in a very natural way:

a // Position[0] // SortBy[Last] // Map[Max]
share|improve this answer
1  
+1 This is the first answer to this question I understand by just reading it :) –  eldo Aug 3 at 21:37
    
Although I think you know I fully agree with you regarding "I am fond of infix notation ... more readable than the 'conventional'" it seems most people disagree. I'm really not sure why. Simple unfamiliarity? –  Mr.Wizard Aug 4 at 0:03
    
Then again this answer has accumulated six votes at present, the last one mine, so perhaps I/we have manged to convince more people? I almost included this infix angle in my own answer then thought: "Nah, I'll get hoisted on a pike for it (again); better not." –  Mr.Wizard Aug 4 at 0:04
1  
Er… is the /* in the last example irreplaceable? // seems to have the same effect. –  xzczd Aug 4 at 4:40
1  
@xzczd, yes you could use // the way I have written it. Perhaps that would be clearer actually. –  Simon Woods Aug 4 at 8:40

I find the value of the new operator forms becomes critical when working with datasets. Consider

titanic = ExampleData[{"Dataset", "Titanic"}];
titanic[Count[#], "survived"] & /@ {True, False, _Missing}
{500, 809, 0}

Derive a data set for analyzing the survival of very young passengers.

cutoff = 8;
youngest = titanic[All, {"age", "survived"}][Select[#age <= cutoff &]];
pts = 
  Table[
    Function[{x, y}, youngest[Select[#age == x && #survived == y &] /* Length]][x, y], 
    {x, Range @ cutoff}, {y, {True, False}}] // Transpose;
ListPlot[Tooltip /@ pts,
  PlotStyle -> {Black, Red},
  PlotMarkers -> {Automatic, 14},
  PlotLegends -> {"Survived", "Perished"},
  AxesLabel -> {"Age", "Count"}]

survival

Without the new operator forms for functions like Count and Select, working with datasets would much more awkward. It is only speculation on my part, but I believe datasets (i.e., structured data) provided the motivation for implementing the new forms.

share|improve this answer
    
In a previous comment it was mentioned how operator forms can be used to refactor code as part of improving readability but also efficiency. As illustrated by other answers, operator forms can replace occurrences of Function (introduced to deal with nested #&'s) suggesting a refactoring in the code of this answer and in particular a dropping of one of the Table's iterators. The snippet Table[youngest[Select[#age == x &] /* CountsBy[#survived &] /* ({#[True], #[False]} &)]//Normal,{x,Range@cutoff}] is equivalent, perhaps of comparable readability but certainly improved efficiency-wise. –  Ronald Monson Aug 7 at 2:21

Very nice answers. I wanted to add something else.

One typical "Mathematica way" of coding involves overloading a function with several definitions, that do different things according to what arguments are passed (I actually abuse this). You can pattern match by head with things like f[x_Integer]:=... and f[x_Real]:=....

I see the Dataset/Query functionality not so much as a reason why the operator forms are useful, but as an example of how they can be useful. Dataset/Query take functions as arguments. Functions aren't very easy to "pattern match" according to what they are for; but with operators, this becomes easy. Dataset/Query behave differently for a _Select argument (descending, filtering function) than a general _Function (ascending).

Now you can design your functions to take functions as arguments, and behave differently if those are functions that apply, functions that map, functions that filter, and do it in a way that's neatly integrated with built-ins

share|improve this answer
    
I think some examples will help me understand your point better. –  RunnyKine Aug 4 at 4:34
    
@RunnyKine These two are different Query[Select[EvenQ], 1]@{{2}} and Query[Select[#, EvenQ] &, 1]@{{2}}. The first one is recognized as descending and treated specially –  Rojo Aug 4 at 4:40
    
@RunnyKine, so, Query is overloaded for "filtering" arguments, and it recognizes them through their heads, in a neat way, thanks to the operator forms. _MaximalBy, _Select, _KeySelect, etc –  Rojo Aug 4 at 4:41
    
@RunnyKine I don't know to what extent doing these kinds of things will become a nice habit of mine, its too soon. People like Leonid or WReach that are more experienced programmers might have a better idea at this point about how important this is. –  Rojo Aug 4 at 4:42
1  
Ah, I see. Thanks for explaining. +1 –  RunnyKine Aug 4 at 4:47

Here's a stab at a second pass: Syntactic sugar shouldn't be underestimated given its cumulative effects (also only a limited number of functions can have shortforms and sometimes for precedence reasons four symbols are needed in the pure form - (#)&)

An example: Suppose it is desired to take keys/values "f" through to "h" and "p" through to "r" in assoc3, an association that associates the nth letter of the alphabet with the number n.

assoc3 = AssociationThread[CharacterRange["a", "z"] -> Range@26];

One solution

Merge[Query[Apply[Span,Partition[Flatten[Map[FirstPosition[Keys@assoc3,#]&,{"f","h","p","r"}]],2],{1}]][assoc3],First]

(* ->    <|"f" -> 6, "g" -> 7, "h" -> 8, "p" -> 16, "q" -> 17, "r" -> 18|> *)

has a natural object being "operated on", {"f","h","p","r"} being pushed deeper into the code and possibly not as clear as using operator forms:

Merge[First]@*(Query[#][assoc3] &)@*(Span@@@#&)@*(Partition[#, 2]&)@*Flatten@((FirstPosition[Keys@assoc3,#]&)/@{"f","h","p","r"})

 (* ->   <|"f" -> 6, "g" -> 7, "h" -> 8, "p" -> 16, "q" -> 17, "r" -> 18|> *)

or something where operator forms are potentially extended to all functions and to include shortform versions

Merge[First]@*Query[][assoc3]@*Span@@@ @*Partition[2]@*Flatten@*FirstPosition[Keys@assoc3]/@{"f","w","s","w"}

 (* ->    <|"f" -> 6, "g" -> 7, "h" -> 8, "p" -> 16, "q" -> 17, "r" -> 18|> *)

(* not actual input/output speculative only *)

At a more abstract level operator forms seem to be a way for harnessing context in that omitted arguments are being supplied by the object being operated on. There are however some functions that surprisingly don't seem to have operator forms:

{Query[Sort[Greater]][{1, 2, 3}], Query[Sort[#, Greater] &][{1, 2, 3}]}
(* ->   {Sort[Greater][{1, 2, 3}], {3, 2, 1}} *)

or that don't operate in certain situations

{Query["Min" -> Min][{1, 2, 3}], Query["Min" -> Min@# &][{1, 2, 3}]}
(* -> {{1, 2, 3}, "Min" -> 1} *)

suggesting the advantages of automating the process of detecting operator forms since this seems closer to the way humans linguistically operate

Consider an operator form of the pangram:

"Illustrate the quick brown fox jumping over the lazy dog" 

Illustrate @* Fox$_{(the, quick,brown)}$ @* JumpingOver @* Dog$_{(the, lazy)}$

or a variation involving more "Center Embedding" a linguistic analog of the progressive enveloping of {"f","h","p","r"}

"Illustrate the fox, the cat the dog the flea bit crippled fought jumping over the lazy dog."

which seems difficult to parse possibly due to limitations in human's short-term memory as we long for a bottoming out to attach subjects to their matching predicates. Alternatively

Illustrate @* Fox$_{(the, quick,\ brown,\ fought\ by\ cat_{crippled \ by\ dog_{bitten\ by\ flea}})}$ @* JumpingOver @* Dog$_{(the, lazy)}$

seems more parseable. These involve more descriptive forms than operational (but the same principle applies) but more operational forms also come in variable order linguistically. Consider

"Illustrate the quick brown fox jumping over the lazy dog and exhibit by first performing gilded framing and then sending to the Louvre by rail."

which when put together in "operator form" expresses:

(Illustrate @* Fox$_{(the, quick,\ brown,\ fought\ by\ cat_{crippled \ by\ dog_{bitten\ by\ flea}})}$ @* JumpingOver @* Dog$_{(the, lazy)}$) // Frame$_{guilded}$ // Send$_{rail}$ // Exhibit$_{Louvre}$

Naturally this could all be enhanced by flexible code-folding (and say tool-tip illustration of the structural change performed by the operator) but the point is it becomes more natural (possible?) with operator form positioning. It also indicates a possible bridging between the linguistic but (destined?) vagueness of wolfram-alpha queries and the precision but non-linguistic form of the Wolfram Language (at least initially in restricted domains)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.