First of all I know that Query
is a nice way to organize your functions that are applying at specific levels of an expression. But I don't understand the order in which they are applied.
Consider the following dataset as an example.
data={
<|"field 1"->1,"field 2"->2,"field 3"->3|>,
<|"field 1"->4,"field 2"->5,"field 3"->6|>,
<|"field 1"->7,"field 2"->8,"field 3"->9|>
}
If I were to apply the following Query on this dataset:
Query[
ReverseSortBy["field 3"],
StringJoin[ToString/@{#"field 1",#"field 2"}]&
]@data
Then I get:
{"78", "45", "12"}
This means that first the function ReverseSortBy["field 3"]
is applied to the entire expression to reverse the order based on "field 3" and then on each sub level the function StringJoin[ToString/@{#"field 1",#"field 2"}]&
is applied to get the joined values from the two fields.
Note the order of application cannot be the other way since if StringJoin[ToString/@{#"field 1",#"field 2"}]&
is applied on each sub level then the association structure is lost and then ReverseSortBy
will not be able to find the Key
"field 3"
by which to reverse the list of associations.
So following the same idea I add another function:
Query[
ReverseSortBy["field 3"]@*Select[#"field 3">3&],
StringJoin[ToString/@{#"field 1",#"field 2"}]&
]@data
The functions must be getting applied from outer to inwards but this fails! Since now magically the order of application has changed from inner to outer.
Note the Map
allows me to move inner level function to outer level and thereby controlling the order precisely as follows to make the above Query
work:
Query[
Map[StringJoin[ToString/@{#"field 1",#"field 2"}]&]@*ReverseSortBy["field 3"]@*Select[#"field 3">3&]
]@data
I get
{"78", "45"}
as expected! But why did the second Query changed the order of function application and failed? What are the rules governing function application order inside Query
?