朱莉娅自定义类型分配 [英] Julia custom type assignment

查看:113
本文介绍了朱莉娅自定义类型分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在julia中为自定义类型分配多个元素。但是我不知道怎么做。或者换句话说,我想重载赋值运算符,以返回该类型中包含的所有元素的元组。

I try to assign multiple elements from a custom type in julia. However I don't know how to do it. Or in other words I would like to overload the assignment operator as to return a tuple of all the elements contained in the type.

这是所需的行为:

type foo
    a
    b
end

(a,b) = foo(1,2)
a
> 1

以下是错误消息:

ERROR: LoadError: MethodError: `start` has no method matching start(::foo)

我的看法是我需要实现一些负责赋值的迭代器,但我不知道怎么做。

My take is that I need to implements some sort of iterator that takes care of the assignment, but I don't know how to do it.

编辑

我实现了start(),done(),next()函数。现在我担心如何仍然允许我分配类型而不是它的元素。

I implemented the "start(), done(), next()" functions. Now I was concerned about how I would still be allowed to assign the type and not it's elements.

写作:

a, b = foo(1,2)
a

# returns
> 1

但是:

a = foo(1,2)
a
# returns
> foo(1,2)

太棒了。因此,julia认识到在
上有一个元素,等式的左边(lhs)将返回右侧的类型,而lhs上的'n'元素将分配来自$的'n'元素b $ b类型。因此,如果要分配整个类型,则必须将类型分配给lhs上的单个元素。而已。

which is fantastic. Hence julia recognizes that having a single element on the left hand side (lhs) of the equation will return the type on the right hand side and having 'n' elements on the lhs will assign 'n' elements from the type. Hence if you want to assign the entire type you have to assign the type to a single element on the lhs. That's it.

推荐答案

赋值使用迭代器协议,因此 start ,<$需要为该类型实现c $ c> done 和 next

The assignment uses the iterator protocol and therefore start, done and next needs to be implemented for the type.

关于样式,类型名称的注释应该以大写字母开头,并且字段最好应该是性能的具体类型。在下面我在 Foo 中引入了一个类型参数 T 。 T可以是任何类型,但Foo的字段具有相同的类型。如果这是限制性附加类型参数,可以引入或者可以为每个字段分配具体类型。

A comment about style, type names should be start with a capital letter and the fields should preferably be concrete types for performance. In the following I have introduced a type parameter T in Foo. T can be any type, but the fields of Foo has the same type. If this is to restrictive additional type parameters, can be introduce or each field could be assigned a concrete type.

下面的示例实现 start Foo 已完成下一步 c>

The example below implements start, done and next for the type Foo

type Foo{T}
    x::T
    y::T 
    z::T
end
Base.start(foo::Foo) = 1
Base.done(foo::Foo, i) = nfields(foo) < i
Base.next(foo::Foo, i) = getfield(foo, i), i+1

通过上面的实现,Foo的内容可以映射到不同的变量:

With the above implemented the content of Foo can be splatted to different variables:

x, y, z = Foo(1, 2, 3)

作为奖励,Foo现在可以在forloop as:

As a bonus, Foo can now be iterated through in a forloop as:

for i in Foo(1, 2, 3)
    println(i)
end

这篇关于朱莉娅自定义类型分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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