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

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

问题描述

有没有一种方法可以在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

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

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