朱莉娅函数声明风格 [英] julia function declaration style

查看:83
本文介绍了朱莉娅函数声明风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Julia中,我知道三种定义命名多行函数的方法:

In Julia, I know of three ways to define a named multiline function:

1.

function f(x, y)
    ...
end

2.

f = function(x, y)
    ...
end

3.

f(x, y) = begin
    ...
end

它们似乎都产生相同的结果.
有什么区别吗?应该使用哪个,为什么?

They all seem to produce the same outcome.
Is there any difference? Which one should be used and why?

推荐答案

1和3在功能上是相同的,但从风格上来说,1是首选. 简短形式函数声明" f(x,y) = …通常用于(鼓励使用)单行定义,即没有begin块.

1 and 3 are functionally identical, but 1 is preferred stylistically. The "short form function declaration" f(x,y) = … is typically used (and encouraged) for one-line definitions — that is, without a begin block.

2是不同的.它正在创建一个 anonymous 函数,然后将其分配给f.请注意,与1和3创建的绑定不同,您实际上可以 ressign f来完全不同.这意味着Julia无法假定f将始终调用该函数,这意味着它无法进行任何常规优化.现在,如果使用const f = function(x, y) …,则f是常量绑定,它的行为应与其他声明类似.但是请注意,f仍然只是对匿名函数的绑定-函数本身不知道其名称!因此它将打印为#1 (generic function with 1 method)而不是f (generic function with 1 method).

2 is different. It's creating an anonymous function, and then assigning it to f. Note that unlike the bindings created by 1 and 3, you can actually reassign f to completely different things. This means that Julia cannot assume that f will always call that function, which means that it cannot do any of its normal optimizations. Now, if you used const f = function(x, y) …, then f is a constant binding and it should behave similarly to the other declarations. But note that f is still just a binding to an anonymous function — the function itself doesn't know what its name is! So it'll print as #1 (generic function with 1 method) instead of f (generic function with 1 method).

请参见 https://docs.julialang.org/en/stable/manual/功能/以获取更多详细信息.

See https://docs.julialang.org/en/stable/manual/functions/ for more details.

这篇关于朱莉娅函数声明风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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