Hacker News new | ask | show | jobs
by matdes 4360 days ago
" λ 5 + 7 12 :: Num a => a What the christ? The 12 I get. Got it. The colons? Not sure. I think it's just a dumb separator. Num is type! What the hell is a => a? I have no idea."

:: means "the stuff after this is the type signature"

Normally, a type signature can be as simple as something like

'x' :: Char

which is the type signature of the character 'x'. Looking at the type signature of 12 shows two parts "Num a =>" and "a". This can be read as "it returns a generic type `a` that must be an instance of the type class Num", which sounds really complicated but isn't.

The "Num a =>" is a type class constraint on the returned type "a". Type classes are basically like interfaces, they set up constraints and methods that need to be implemented for that type, analogous to how in other languages a class can implement an interface. For example, the Eq type class mandates you define the (==) and (/=) methods for that type, analogous to how something like the interface Comparable in Java requires you to define the compareTo method.

Thus the concrete type "Integer" is an instance of type class "Eq" because it implements those (==) and (/=)

Num is an example of a type class, just like Eq. But Num requires you to define a few more methods

  class Num a where
  (+) :: a -> a -> a
  (*) :: a -> a -> a
  (-) :: a -> a -> a
  negate :: a -> a
  abs :: a -> a
  signum :: a -> a
  fromInteger :: Integer -> a
So all of the things you think of as "numbers" are all types that implement "Num", e.g. an Integer, a Float, a Double.

So going back, "12 :: Num a => a" means 12 can be any type which implements Num, which is really just a fancy way of saying "this number can be cast into any numeric type". You can perform this casting manually!

  λ (5 + 7) :: Integer
 12:: Integer
  
  λ (5 + 7) :: Float
  12.0:: Float