Personal tools

Newtype

From HaskellWiki

Revision as of 20:33, 2 September 2006 by NeilMitchell (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

One frequent question is what is the difference between data and newtype? The answer has to do with the level of undefinedness that occurs in the values. The following sample code shows how three different data declarations behave with undefined present.

module Foo where
 
data Foo1 = Foo1 Int
data Foo2 = Foo2 !Int
newtype Foo3 = Foo3 Int
 
x1 = case Foo1 undefined of
     Foo1 _ -> 1		-- 1
 
x2 = case Foo2 undefined of
     Foo2 _ -> 1		-- undefined
 
x3 = case Foo3 undefined of
     Foo3 _ -> 1		-- 1
 
y1 = case undefined of
     Foo1 _ -> 1		-- undefined
 
y2 = case undefined of
     Foo2 _ -> 1		-- undefined
 
y3 = case undefined of
     Foo3 _ -> 1		-- 1