【问题标题】:chaining functions with multiple outputs in juliaJulia中具有多个输出的链接函数
【发布时间】:2018-08-25 13:55:07
【问题描述】:

Julia 对使用 |> 之类的链接函数有很好的支持

x |> foo |> goo

但是对于具有多个输入和多个输出的函数,这不起作用:

julia> f(x, y) = (x+1, y+1)
julia> f(1, 2)
(2, 3)
julia> (1,2) |> f |> f
ERROR: MethodError: no method matching f(::Tuple{Int64,Int64})
Closest candidates are:
  f(::Any, ::Any) at REPL[3]:1
Stacktrace:
[1] |>(::Tuple{Int64,Int64}, ::typeof(f)) at ./operators.jl:813
[2] top-level scope at none:0

我们可以定义f 来接受元组以使其工作。

julia> g((x,y)) = (x+1, y+1)
julia> (1,2) |> g |> g
(3, 4)

g的定义不如f明确。在 julia 的文档中,我读到函数正在调用元组,但实际上存在差异。

有什么优雅的解决方案吗?

【问题讨论】:

    标签: function tuples julia chain


    【解决方案1】:

    你也可以像这样使用喷溅操作符...

    julia> f(x, y) = (x+1, y+1)
    f (generic function with 1 method)
    
    julia> (1,2) |> x->f(x...) |> x->f(x...)
    (3, 4)
    

    【讨论】:

      【解决方案2】:

      或者你可以使用数组

      julia> f(x) = [x[1]+1,x[2]+1]
      f (generic function with 1 method)
      
      julia> [1,2] |> f |> f
      2-element Array{Int64,1}:
       3
       4
      

      【讨论】:

        猜你喜欢
        • 2016-06-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 2017-03-19
        • 2012-02-01
        • 1970-01-01
        • 2016-07-26
        • 1970-01-01
        相关资源
        最近更新 更多