I would like to do something like this,
pt_to_line_dist(x::SVector{N-1},l::SVector{N}) where N <: UInt = print("hi")
Is it possible?
I would like to do something like this,
pt_to_line_dist(x::SVector{N-1},l::SVector{N}) where N <: UInt = print("hi")
Is it possible?
no
Math on type parameters is not possible. Also, your N <: UInt
will not do what you expect. In this case, it’s likely that N isa Int
(not isa UInt
and definitely not <:UInt
, which could only apply to a type rather than value). Note that isa
is not something you can do with type parameters anyway.
You could implement this as
function pt_to_line_dist(x::SVector{N},l::SVector{M}) where {N,M}
if N == M-1
print("hi")
else
# do other stuff or throw an error
end
end
Although in this case I wouldn’t bother with type parameters at all
function pt_to_line_dist(x::AbstractVector,l::AbstractVector)
if length(x) == length(l)-1
print("hi")
else
# do other stuff or throw an error
end
end
When given SVector
s for inputs, length
will evaluate to a compile-time constant and the if
/else
block will get compiled away, leaving only the correct branch. When given non-static vectors, the code will still work but it will have to check at run-time which branch to use.