Julia 函数声明风格 [英] julia function declaration style

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

问题描述

在 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 创建的绑定不同,您实际上可以重新分配 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.

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

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