朱莉娅的convert()什么时候使用? [英] When is Julia's convert() used?

查看:110
本文介绍了朱莉娅的convert()什么时候使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://julia.readthedocs.org/en/最新/手动/转换和促销/,这里有关于将整数添加到浮点数的讨论,等等,最后它说

At http://julia.readthedocs.org/en/latest/manual/conversion-and-promotion/, there is a discussion about adding integers to floats and so on, and and at the end it says

用户定义的类型可以轻松地加入此促销系统,方法是定义用于与其他类型之间进行转换的方法,并提供一些促销规则来定义将其与其他类型混合时应提升为哪种类型.

User-defined types can easily participate in this promotion system by defining methods for conversion to and from other types, and providing a handful of promotion rules defining what types they should promote to when mixed with other types.

据此我推断,在定义自己的数字类型时,我只需要定义如何将其转换为已知类型以使其与函数一起工作即可.但是我尝试了一下,但似乎不起作用:

From this I inferred that when defining my own numeric type, I simply needed to define how to convert it to a known type for it to work with functions on it. But I tried this and it doesn't seem to work:

julia> type MyType
           n::Int
       end

julia> convert(::Type{Int}, x::MyType) = x.n
convert (generic function with 1 method)

julia> convert(Int, MyType(1))
1

julia> MyType(1) + 1
ERROR: `+` has no method matching +(::MyType, ::Int64)

推荐答案

您的代码有两个问题:

  • 算术运算符,例如+仅提升Number的子类型;
  • 除了转换功能之外,您还需要定义一个促销规则.
  • arithmetic operators such as + only promote subtypes of Number;
  • you need to define a promotion rule in addition to the conversion function.

以下应做您想做的事:

module Test

import Base: convert, promote_rule

type MyType <: Number
    n :: Int
end

convert(::Type{Int}, x::MyType) = x.n

promote_rule(::Type{MyType}, ::Type{Int}) = Int

end

这篇关于朱莉娅的convert()什么时候使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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