Skip to content

Commit

Permalink
Recurse _ past ternary operator (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
mcabbott authored Nov 5, 2020
1 parent fc332c4 commit 3595315
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Underscores.jl
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ function lower_inner(ex)
# Infix operators do not count as outermost function call
return Expr(ex.head, ex.args[1],
map(lower_inner, ex.args[2:end])...)
elseif ex.head in _square_bracket_ops
elseif ex.head in _square_bracket_ops || ex.head == :if
# Indexing & other square brackets not counted as outermost function
return Expr(ex.head, map(lower_inner, ex.args)...)
elseif ex.head == :. && length(ex.args) == 2 && ex.args[2] isa QuoteNode
Expand Down Expand Up @@ -207,6 +207,10 @@ This excludes the following operations:
and hence to pass the anonymous function to `sum` instead. This also applies to
broadcasted operators, such as `map(_^2,x) ./ length(x)`.
* If statements, including the ternary operator. Note that this has higher
precedence than pipes: `data |> (any(_.x<0, __) ? abs.(__) : __) |> step`
needs these brackets.
The scope of `__` is unaffected by these concerns.
| Expression | Meaning |
Expand All @@ -217,6 +221,7 @@ The scope of `__` is unaffected by these concerns.
| `@_ sum(_^2,a) / length(a)` | `sum(x->x^2,a) / length(a)` |
| `@_ /(sum(_^2,a), length(a))` | The same, infix form is canonical. |
| `@_ data \\|> filter(_>3,__).^2` | `data \\|> d->(filter(>(3),d).^2)` |
| `@_ any(_>3,xs) ? 0 : map(_,ys)` | `any(x->x>3,xs) ? 0 : map(y->y,ys)`|
"""
macro _(ex)
Expand Down
4 changes: 4 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ using Test
# Multiple args
@test [0,0] == @_ map(_-_, [1,2])

# Ternary
@test ["a","b","c"] == @_ data |>
(any(_.y>2, __) ? map(_.x, __) : map(_.y, __))

# Use with piping and __
@test [1] == @_ data |>
filter(startswith(_.x, "a"), __) |>
Expand Down

0 comments on commit 3595315

Please sign in to comment.