如何将参数列表传递给Julia中的函数 [英] How to pass parameter list to a function in Julia

查看:106
本文介绍了如何将参数列表传递给Julia中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Julia语言的新手,并且该教程还不是很深入,我还不明白传递函数参数列表的最佳方法是什么.我的函数如下所示:

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 this:

function dxdt(x)
    return a*x**2 + b*x - c
end

其中x是变量(二维数组),a,c和d是参数.据我了解,不建议在Julia中使用全局变量.那么正确的方法是什么?

where x is the variable (2D array) and a,c, and d are parameters. As I understand it is not recommended to work with global variables in Julia. So what is the right way to do it?

推荐答案

惯用的解决方案是创建一个用于保存参数的类型,并使用多个分派来调用函数的正确版本.

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.

这就是我可能要做的

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

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

有时候,如果一个类型有很多字段,我会定义一个如下所示的辅助函数_unpack(或任何您想命名的函数):

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)

然后我可以将dxdt的实现更改为

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

这篇关于如何将参数列表传递给Julia中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆