Daniel Fath
Daniel Fath

Reputation: 18109

How does Haskell actually define the + function?

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.

Upvotes: 10

Views: 521

Answers (2)

nponeccop
nponeccop

Reputation: 13677

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.

Upvotes: 5

augustss
augustss

Reputation: 23014

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.

Upvotes: 21

Related Questions