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

查看:39
本文介绍了`where {t:<在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被转换为整数,然后用于显式键入xy.但是,为什么不只是x::Int64呢? where {T :< Integer}是否允许诸如Int32Int64的任何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:&lt;在Julia函数声明的上下文中是“整数"的意思吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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