Le dimanche 25 mai 2014 08:29:02 UTC+2, James Crist a écrit :
>
> I've been struggling with this for a while, and haven't found a way to do 
> it that I'm happy with. I'm sure there is one though. Basically, I want to 
> declare a function that works on an array of floats. Doesn't matter what 
> kind of float. Doesn't matter if there are 2 different kinds of float 
> arrays.
>
> For example, if `a` is an array of Float64, and `b` is an array of 
> Float32, the function foobar(a, b) should work, just as well as f(a, a) or 
> f(b, b). I've gotten a couple ways to work, but am not sure what's the most 
> Julian, and have to believe there is a better way:
>
> 1.) Parametric definition. This gets really long if there are multiple 
> different Matrices in the call.
> function foobar{T<:FloatingPoint, S<:FloatingPoint}(a::Matrix{T}, b::
> Matrix{S})
>
> There seems to be an inconsistency with type definition:
function foo(a::FloatingPoint, b::FloatingPoint)
    return a+b
end
or with explicit promotion:
function foo(a::FloatingPoint, b::FloatingPoint)
    a, b = promote(a, b)
    return a+b
end
are working well. 

As well,
x = convert(Array{Float16}, rand(2))
x + rand(2)
is working ok (explicit promotion can also be done).

This would gracefully solve your problem.

But,
function foo(a::Array{FloatingPoint}, b::Array{FloatingPoint})
    a + b
end 
is unfortunately not working. I don't know whether this is a bug or a 
choice.


 

> 2.) Type union definition. Not sure if this is optimal or not. It also 
> will only work with the initial defined floats, so anything that subtypes 
> FloatingPoint later on will not be valid
> FloatArrays = Union(Matrix{Float16}, Matrix{Float32}, Matrix{Float64})
>
> function foobar(a::FloatArrays, b::FloatArrays)
>
> Am I making this problem more complicated than it needs to be? What is the 
> correct way to do this?
>

Reply via email to