问题
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.
Here is the desired behavior:
type foo
a
b
end
(a,b) = foo(1,2)
a
> 1
and here is the error message:
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.
EDIT
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.
Writing:
a, b = foo(1,2)
a
# returns
> 1
however:
a = foo(1,2)
a
# returns
> foo(1,2)
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.
回答1:
The assignment uses the iterator protocol and therefore start, done and next needs to be implemented for the type.
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.
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
With the above implemented the content of Foo can be splatted to different variables:
x, y, z = Foo(1, 2, 3)
As a bonus, Foo can now be iterated through in a forloop as:
for i in Foo(1, 2, 3)
println(i)
end
回答2:
I don't know how to overload the assignment operator, but you can return all the fields with this function:
all_fields(x) = [x.(i) for i = 1:nfields(x)]
Then you can do
(a,b) = all_fields(foo(1,2))
来源:https://stackoverflow.com/questions/38289726/julia-custom-type-assignment