>
> Is x = copy(y) the same as x = y for immutables??

For this question the @which macro is very useful. It tells you that

julia> @which copy(1)
copy(x::Union(AbstractString,TopNode,LambdaStaticData,(Any...,),Symbol,DataType,UnionType,Function,QuoteNode,Number))
at operators.jl:174

and that definition is just a no-up, so the answer is yes for the types in
that defintion.

Is there a better way using dispatch? Something like SetMax!{K<Immutable,
> V<Mutable}


I have often wanted to dispatch of Mutable/Immutable, but these properties
go across of the declared type tree. My understand is that the declared
subtype relation will also in the future be restricted to have one
supertype, i.e. a tree structure, and therefore it doesn't seem likely that
you'll be able to write a type the way you proposed.

2014-12-30 8:56 GMT+01:00 Greg Plowman <greg.plow...@gmail.com>:

>
> I am trying to define a composite type for holding pairs (similar to Dict,
> I suppose), where I keep track of a max key and associated value.
>
> I want to define a function that checks and sets new max as below:
>
>
> type MaxPair{K,V}
>     key::K
>     value::V
> end
>
> function SetMax!{K,V}(pair::MaxPair{K,V}, key::K, value::V)
>     if key > pair.key
>         copy!(pair.key, key)
>         copy!(pair.value, value)
>     end
>     return pair
> end
>
> I originally had:
> pair.key = copy(key)
> pair.value = copy(value)
> which worked fine, but in my case key is usually Int, and value is some
> sort of array (or possibly composite type).
>
> For efficiency I thought the in-place copy!() would be better, but copy!()
> is not defined for Int (presumably for immutable types in general).
> I could of course, use
> pair.key = copy(key)  # should this just be pair.key = key for immutables
> copy!(pair.value, value)
>
> Is x = copy(y) the same as x = y for immutables??
>
> but in an effort to keep type general, I thought the following might work
>
> function SetMax!{K,V}(pair::MaxPair{K,V}, key::K, value::V)
>     if key > pair.key
>         if isimmutable(pair.key)
>             pair.key = key
>         else
>             copy!(pair.key, key)
>         end
>
>         if isimmutable(pair.value)
>             pair.value = value
>         else
>             copy!(pair.value, value)
>         end
>     end
>     return pair
> end
>
> Is anything wrong with this?
>
> Is there a better way using dispatch?
> Something like SetMax!{K<Immutable, V<Mutable}
>
> Thanks, Greg
>
>

Reply via email to