Fazeleh
Fazeleh

Reputation: 1128

How to call a parameter list from a function in Julia

how can I call function dxdt ? I don't know how to define p as a argument for calling the function.

type Params
    a::TypeOfA
    b::TypeOfB
    c::TypeOfC
end

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

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

Upvotes: 0

Views: 268

Answers (2)

Ian Marshall
Ian Marshall

Reputation: 739

Is your question just how you define a variable p of type Params? For a = 1.0, b = 2.0, c = 3.0:

p = Params(1.0,2.0,3.0)

Which can be used in the following way:

type Params
       a::Float64
       b::Float64
       c::Float64
end

p = Params(1.0,2.0,3.0)

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

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

dxdt(1.0,p)
6.0

I think that's what you're asking but I'm not sure.

Upvotes: 1

Chris Rackauckas
Chris Rackauckas

Reputation: 19132

Check out Parameters.jl. It has a macro for doing this with more sugar and less typing. I think that's what you're looking for?

using Parameters

@with_kw type A
  a::Int = 6
  b::Float64 = -1.1
  c::UInt8
end

# Safe Way
function dxdt(x, p)
    @unpack a,b,c = p # This works on any type
    a*x^2 + b*x + c
end

# Easy Way
function dxdt(x, p)
    @unpack_A p # This only works on instances of A
    a*x^2 + b*x + c
end

Upvotes: 2

Related Questions