Chain.jl icon indicating copy to clipboard operation
Chain.jl copied to clipboard

"Can't insert a first argument into"

Open jtrakk opened this issue 4 years ago • 2 comments

julia> 5 |> @chain identity
5

julia> 5 |> @chain (x->x)
ERROR: LoadError: Can't insert a first argument into:
begin
    #= REPL[5]:1 =#
    x
end.

First argument insertion works with expressions like these, where [Module.SubModule.] is optional:

[Module.SubModule.]func
[Module.SubModule.]func(args...)
[Module.SubModule.]func(args...; kwargs...)
[Module.SubModule.]@macro
[Module.SubModule.]@macro(args...)
@. [Module.SubModule.]func

Stacktrace:
  [1] error(s::String)
    @ Base ./error.jl:33
  [2] insertionerror(expr::Expr)
    @ Chain ~/.julia/packages/Chain/wUcPF/src/Chain.jl:13
  [3] insert_first_arg(e::Expr, firstarg::Symbol)
    @ Chain ~/.julia/packages/Chain/wUcPF/src/Chain.jl:89
  [4] rewrite(expr::Expr, replacement::Symbol)
    @ Chain ~/.julia/packages/Chain/wUcPF/src/Chain.jl:104
  [5] rewrite_chain_block(block::Expr)
    @ Chain ~/.julia/packages/Chain/wUcPF/src/Chain.jl:211
  [6] var"@chain"(__source__::LineNumberNode, __module__::Module, block::Expr)
    @ Chain ~/.julia/packages/Chain/wUcPF/src/Chain.jl:245

The docs say

the result of the previous expression is used as the first argument in the current expression, as long as it is a function call, a macro call or a symbol representing a function

(x->x) is not a function call, macro call, or symbol representing a function, so an error is ok. But maybe it could support this anyway, expanding the API from "symbol representing a function" to "expression representing a function".

If you don't like it I can always go (x->x)(_), so it's not a very big problem, but it might be good.

jtrakk avatar Oct 04 '21 23:10 jtrakk

I ran into this today and found the error message to be confusing. I have a @chain of many transforms, and this is the problem:

if variable_1 != nothing transform(:column_1 => x -> variable_1, renamecols = false) end

So yeah now its obvious that @chain doesn't know where to put the dataframe. Fixed with:

if variable_1 != nothing transform(_, :column_1 => x -> variable_1, renamecols = false) end
                                  ^^^ -- underscore here

mahiki avatar Apr 07 '23 00:04 mahiki

The problem with writing out expressions to the user (in this case the one that Chain doesn't know how to insert the first arg into) is that they look different than what the user typed, so it can be a bit difficult to map back to the offending code. Maybe the error message can be improved.

jkrumbiegel avatar Apr 07 '23 06:04 jkrumbiegel