Skip to content

Commit 40d3596

Browse files
authored
Manual: anonymous function in pipeline needs parentheses (#43661)
Consider: ```julia d = (1:10 .|> x -> x^2 |> sum ) ``` This seems to compute a sum of squares. But it does not. It outputs a vector of squares. (Because `|> sum` is parsed as being part of the anonymous function's body). Parentheses are needed for the desired (expected?) behaviour: ```julia d = (1:10 .|> (x -> x^2) |> sum ) ``` This PR adds a small note and example to the "Function composition and piping" section of the manual to flag this. As an aside, this confusion is even present in the [docstring](https://docs.julialang.org/en/v1/base/base/#Base.:|%3E) for `|>`: > Applies a function to the preceding argument. This allows for easy function chaining. > ```julia [1:5;] |> x->x.^2 |> sum |> inv ``` This is parsed as ```julia [1:5;] |> x-> (x.^2 |> sum |> inv) ``` but it feels like the author meant ```julia [1:5;] |> (x-> x.^2) |> sum |> inv) ```.
1 parent c61cd12 commit 40d3596

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

doc/src/manual/functions.md

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -912,7 +912,7 @@ julia> (sqrt ∘ sum)(1:10)
912912
7.416198487095663
913913
```
914914

915-
The pipe operator can also be used with broadcasting, as `.|>`, to provide a useful combination of the chaining/piping and dot vectorization syntax (described next).
915+
The pipe operator can also be used with broadcasting, as `.|>`, to provide a useful combination of the chaining/piping and dot vectorization syntax (described below).
916916

917917
```jldoctest
918918
julia> ["a", "list", "of", "strings"] .|> [uppercase, reverse, titlecase, length]
@@ -923,6 +923,19 @@ julia> ["a", "list", "of", "strings"] .|> [uppercase, reverse, titlecase, length
923923
7
924924
```
925925

926+
When combining pipes with anonymous functions, parentheses must be used if subsequent pipes are not to parsed as part of the anonymous function's body. Compare:
927+
928+
```jldoctest
929+
julia> 1:3 .|> (x -> x^2) |> sum |> sqrt
930+
3.7416573867739413
931+
932+
julia> 1:3 .|> x -> x^2 |> sum |> sqrt
933+
3-element Vector{Float64}:
934+
1.0
935+
2.0
936+
3.0
937+
```
938+
926939
## [Dot Syntax for Vectorizing Functions](@id man-vectorized)
927940

928941
In technical-computing languages, it is common to have "vectorized" versions of functions, which

0 commit comments

Comments
 (0)