Julia:实现类型的标准数学运算 [英] Julia: implement standard math operations for types

查看:14
本文介绍了Julia:实现类型的标准数学运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 julia 中为用户创建的类型实现基本算法

Is there a way to implement basic arithmetic for user created types in julia

例如:

type Foo
    bar::Float32
    foo::Int32
end
a = Foo(3.23,23)
b = Foo(4.56,54)
c = a+b

如果可能的话,我该怎么做?提前致谢

How, if at all possible can I do this? Thanks in advance

推荐答案

您需要显式导入 Base 函数,以便为您自己的类型添加方法.我不确定这是否是最好的方法,但以下方法可以让您将两个 Foos 添加在一起.

You need to explicitly import the Base functions for adding methods for your own types on them. I'm not sure if this the best way to do it, but the following would enable you to add two Foos together.

type Foo
bar::Float32
foo::Int32
end

import Base: +
+(a::T, b::T) where {T<:Foo} = Foo(a.bar+b.bar, a.foo+b.foo)

a = Foo(3.23,23)
b = Foo(4.56,54)
c = a+b

这篇关于Julia:实现类型的标准数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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