`where {t:<在Julia函数声明的上下文中是“整数"的意思吗? [英] What does the `where {t :< Integer}` mean in the context of a function declaration in Julia?
问题描述
我已经在其他人的代码中看到了以下内容,但是由于我不了解发生了什么,所以我从来没有自己写过它.
I have seen the following in other people's code, but I've never written it in my own since I didn't understand what was happening.
例如:
function add(x::T, y::T) where {T :< Integer}
我猜想T
被转换为整数,然后用于显式键入x
和y
.但是,为什么不只是x::Int64
呢? where {T :< Integer}
是否允许诸如Int32
和Int64
的任何Int类型?
I am guessing that T
is being cast as an Integer and then used to explicitly type x
and y
. But why not just do x::Int64
? Does where {T :< Integer}
allow for any Int type like Int32
and Int64
?
推荐答案
在Oscar的回答上稍微扩展一下:
To expand a little on Oscar's answer:
使用function add(x::T, y::T) where {T :< Integer}
可以将参数方法添加到功能add(x, y)
.您可以在 Julia文档下的[参数方法.
Using function add(x::T, y::T) where {T :< Integer}
allows you to add a parametric method to the function add(x, y)
. You can read up on this in more detail in the Julia documentation under Parametric Methods.
这具有两个主要优点:
它允许您定义合理的通用方法(因为在许多情况下,整数的确切类型不会真正影响函数定义).同时,它允许您将调用限制为相同类型的x, y
对,这可以提高类型的稳定性并导致更高效的编译代码.
This comes with two big advantages:
It allows you to define reasonably general methods (since in many cases the exact type of integer would not really affect the function definition). Simultaneously it allows you to restrict the call to x, y
pairs of the same type, which can improve type stability and lead to more efficient compiled code.
这篇关于`where {t:<在Julia函数声明的上下文中是“整数"的意思吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!