Constraints on parametrized abstract types

question

#1

Is there any mechanism for constraining numerical parameters of abstract types?

abstract Var{dim<:Integer} # can we enforce dim > 0 ?

#2

I’m not aware of such a capacity, but dim <: Integer doesn’t make any sense since <: compares two types, but dim isn’t a type.

I wouldn’t worry about this. It’s not going to be the main source of bugs in any program you write.


#3

@johnmyleswhite isn’t dim<:Integer the syntax to constrain the parameter type in a declaration? What is the effect of writing it?


#4

In type definitions, that syntax checks that dim is a specific type (like Int64) and doesn’t check that dim is a specific number.


#5

I know, that is the reason I asked the question. I know how to constrain types, but not values.


#6

In principle you could define a new type PositiveInteger as

immutable PositiveInteger <: Integer
     i::Int

     PositiveInteger(i) = i > 0 ? new(i) : throw(ArgumentError("Only positive integers allowed"))
end

and restrict the type to be a subtype of PositiveInteger.


#7

Thank you @dpsanders I was just wondering if such behavior could be enforced with syntax. I agree with @johnmyleswhite when he says that this enforcement is not something I should be worried about. It is very unlikely that a user will misuse the type with a negative dimension.


#8

I’ve been thinking about the same thing for the Tau.jl package. The idea there is to overload operators like * to yield pi*2 == tau, but allowing the remaining values to work as usual, i.e. converting to float. This is based on a comment by @StefanKarpinski here:

Perhaps that’s good reason to have tau in Base: it’s a more exact way to express 2pi as an Irrational.

So far it seems I’ll have to rely on PatternDispatch.jl, but I’ll be following this thread closely in case something else comes up :slight_smile:


#9

The confusion stems from a slight sloppiness in you question. You were referring to dim both as a type (parameter) and as a value:

I think you can dispatch on values using “value types”: http://docs.julialang.org/en/stable/manual/types/#value-types , but I don’t think that works for “greater than”, only equality. Also, I hear it’s not a good idea, in most cases.


#10

Thank you @DNF, I thought of value types too initially, but as you said they only work with equalities.