Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "number" in elm

Tags:

types

elm

I'm getting confused by number. It seems to be a type, similar to a supertype of Int and Float, like java.lang.Number, but:

  • It is written in lowercase and thus is syntactically similar to the name of a value (I use 'value' to avoid using the designation 'constant variable')
  • One can actually declare a value called number.

Observe:

> 1024
1024 : number
> 1024.0
1024 : Float
> floor(1024)
1024 : Int

Let's use a value name number:

> number = 144
144 : number
> number
144 : number
> number = floor(144)
144 : Int
> number
144 : Int

And also:

> Result.Ok 12 
Ok 12 : Result error number
> Result.Ok 12.0 
Ok 12 : Result error Float
> Result.Ok (floor 12) 
Ok 12 : Result error Int

What is number?

Is it a union type that has been awkwardly named? An infelicity in the syntax?

(Whimsical aside: Why not have a special syntax for "things from the universe of types" like, ↑Int and another for for "things from the universe of metatypes" like ⇈X. Elm, being by design annotation-poor is sometimes hard to decipher.)

like image 204
David Tonhofer Avatar asked Oct 06 '18 11:10

David Tonhofer


1 Answers

From what I understand, number is a kind of built-in type class, similar to an interface in Java that describes which operations can be performed on the types that implement the interface. But where in Java an interface from a consumer point of view is specified as an ordinary type, a type class is a constraint on a type variable, specified by convention using "magic" type variable names such as number or comparable.

In languages with "proper" type class support, such as Haskell, you would specify the constraint separately, i.e. Number a => a -> a. But in Elm, having just a few built-in type classes, the burden of having to learn the concept and syntax for this just to be able to use a few fairly intuitive built-in type classes I think is seen as unnecessary. While you probably won't intuitively understand exactly what it means, you should be able to understand it well enough to at least be able to use most functions taking numbers or comparables as arguments. Its exact meaning can then be explained later (though I do sometimes wonder how much later the official explanation is going to be...).

I hope this sufficiently answers your question, but let me know if it's still unclear.

like image 132
glennsl Avatar answered Oct 31 '22 11:10

glennsl