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