How to pass parameter list to a function in Julia

后端 未结 5 706
名媛妹妹
名媛妹妹 2021-01-25 07:27

I am newbie in Julia language, and the tutorial is not very deep yet and I didn\'t understand what is the best way to pass a parameter list of a function. My function looks like

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 07:40

    The idiomatic solution would be to create a type to hold the parameters and use multiple dispatch to call the correct version of the function.

    Here's what I might do

    type Params
        a::TypeOfA
        b::TypeOfB
        c::TypeOfC
    end
    
    function dxdt(x, p::Params)
        p.a*x^2 + p.b*x + p.c
    end
    

    Sometimes if a type has many fields, I define a helper function _unpack (or whatever you want to name it) that looks like this:

    _unpack(p::Params) = (p.a, p.b, p.c)
    

    And then I could change the implementation of dxdt to be

    function dxdt(x, p::Params)
        a, b, c = _unpack(p)
        a*x^2 + b*x + c
    end
    

提交回复
热议问题