Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Haskell actually define the + function?

Tags:

haskell

While reading Real world Haskell I came up with this note:

ghci> :info (+)
  class (Eq a, Show a) => Num a where
  (+) :: a -> a -> a
  ...
  -- Defined in GHC.Num
  infixl 6 +

But how can Haskell define + as a non-native function? At some level you have to say that 2 + 3 will become assembler i.e. machine code.

like image 688
Daniel Fath Avatar asked Nov 18 '11 14:11

Daniel Fath


2 Answers

The + function is overloaded and for some types, like Int and Double the definition of + is something like

instance Num Int where
    x + y = primAddInt x y

where primAddInt is a function the compiler knows about and will generate machine code for.

The details of how this looks and works depends on the Haskell implementation you're looking at.

like image 133
augustss Avatar answered Oct 11 '22 06:10

augustss


It is in fact possible to define numbers without ANY native primitives. There are many ways, but the simplest is:

data Peano = Z | S Peano

Then you can define instance Num for this type using pattern-matching. The second common representation of numbers is so called Church encoding using only functions (all numbers will be represented by some obscure functions, and + will 'add' two functions together to form third one).

Very interesting encodings are possible indeed. For example, you can represent arbitrary precision reals in [0,1) using sequences of bits:

data RealReal = RealReal Bool RealReal | RealEnd

In GHC of course it is defined in a machine-specific way by using either primitives or FFI.

like image 44
nponeccop Avatar answered Oct 11 '22 06:10

nponeccop