`where {t :< 是什么意思?Integer}` 在 Julia 函数声明的上下文中是什么意思? [英] What does the `where {t :< Integer}` mean in the context of a function declaration in Julia?

查看:14
本文介绍了`where {t :< 是什么意思?Integer}` 在 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.

举个例子:

函数 add(x::T, y::T) 其中 {T :<整数}

我猜测 T 被转换为整数,然后用于显式键入 xy.但是为什么不直接做 x::Int64 呢?在哪里 {T :<Integer} 允许任何 Int 类型,例如 Int32Int64?

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).您可以在 参数方法.

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 :&lt; 是什么意思?Integer}` 在 Julia 函数声明的上下文中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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