Why is Julia not inferring the output type of f(x,y)=x+y?

Julia’s type inference algorithm needs to keep compilation time “reasonably small” while also computing precise type information where it “seems likely” that this would result in fast code at runtime.

Fast code machine code can generally be produced when type inference can compute concrete types (or small Unions of concrete types). But when an abstract type like Number is encountered with many subtypes, it’s unlikely to be better to infer Number than to widen the type to Any. So type inference has just chosen to widen the type here, computing a less precise result in favor of lowering compilation time.

By the way, here’s the subtypes of Number defined in Base. There’s also many others in external libraries:

Number
├─ Complex
└─ Real
   ├─ AbstractFloat
   │  ├─ BigFloat
   │  ├─ Float16
   │  ├─ Float32
   │  └─ Float64
   ├─ AbstractIrrational
   │  └─ Irrational
   ├─ Integer
   │  ├─ Bool
   │  ├─ Signed
   │  │  ├─ BigInt
   │  │  ├─ Int128
   │  │  ├─ Int16
   │  │  ├─ Int32
   │  │  ├─ Int64
   │  │  └─ Int8
   │  └─ Unsigned
   │     ├─ UInt128
   │     ├─ UInt16
   │     ├─ UInt32
   │     ├─ UInt64
   │     └─ UInt8
   └─ Rational

In short, yes.

2 Likes