On Monday, December 8, 2014 12:15:23 PM UTC-5, Utkarsh Upadhyay wrote:
>
> I have just tried playing with Julia and I find myself often copying 
> `immutable` objects while changing just one field:
>
> function setX(pt::Point, x::Float64)
>   # Only changing the `x` field
>   return Point(x, pt.y, pt.z, pt.color, pt.collision, pt.foo, pt.bar);
> end
>
> Is there is any syntactical sugar to avoid having to write out all the 
> other fields which are not changing (e.g. pt.y, pt.z, etc.) while creating 
> a new object?
> Apart from making the function much easier to understand, this will also 
> make it much less of a hassle to change fields on the type.
>
> Thanks.
>

I played with it some more and this seems to work:

defn = setdiff(names(Point), [:x])
 @eval Point(x, $([:(pt.$n) for n in defn]...))

Of course, this will only work for the x parameter which comes first in the 
field list. I'm not sure how you might extend it to arguments in the middle 
of the list, but maybe you can figure it out.

Reply via email to