[Haskell-cafe] OOP'er with (hopefully) trivial questions.....

Thomas Davie tom.davie at gmail.com
Mon Dec 17 07:35:08 EST 2007


On 17 Dec 2007, at 12:22, Nicholls, Mark wrote:

> Ok...
>
> Thanks I need to revisit data and newtype to work out what the
> difference is I think.

Beware in doing so -- type, and newtype are not the same either.  type  
creates a type synonim.  That is, if I were to declare

type Jam = Int

then Jam and Int from that point on become completely interchangable,  
the only thing this does is make things readable.  For example, a  
parser might be described as a function that takes a list of tokens,  
and outputs a parse tree, and a list of unparsed tokens:

type Parser = [Token] -> (ParseTree, [Token])

if I write some parser combinators, I can now give them clear types like

<|> :: Parser -> Parser -> Parser

I could however still write this, and it would have *exactly* the same  
meaning.

<|> :: ([Token] -> (ParseTree, [Token])) -> ([Token] -> (ParseTree,  
[Token])) -> [Token] -> (ParseTree, [Token])

newtype on the other hand introduces a new type to the type system.   
Because of this, the type system has to be able to tell when you're  
using your new type, so a tag gets attached.

newtype Ham = Ham Int

This creates a type that contains only an integer, but is different  
from Int (and Jam) in the type system's eyes.  Thus, I cannot for  
example write

(Ham 5) + (Ham 6)

Because Ham is not Int and thus (+) does not work (or actually, more  
specifically, Ham is not a member of the class Num, the numeric types,  
and therefore (+) doesn't work).  This can of course be fixed thus:

newtype Ham = Ham Int deriving Num

Hope that helps

Tom Davie

p.s. Sorry for the slip with the newtype Rectangle.


More information about the Haskell-Cafe mailing list