[Haskell-cafe] difference between type and newtype
daniel.is.fischer at web.de
Fri Aug 25 19:27:38 EDT 2006
Am Freitag, 25. August 2006 23:55 schrieb Andrea Rossato:
> Il Fri, Aug 25, 2006 at 08:35:01PM +0100, Brian Hulley ebbe a scrivere:
> > It is maybe easier to just think of a newtype decl as being the same as a
> > data decl except for the fact that you can only have one constructor on
> > the rhs whereas a data decl allows multiple constructors, and a type decl
> > by contrast as just introducing a simple alias for convenience.
> First my apologies for being a bit confusing in my question: I'm tired
> and wrote the code too quickly...;-)
> So I'll rephrase:
> type T a = Int -> (a, Int)
> mkT :: a -> T a
> mkT a = \x -> (a, x)
> newtype T1 a = T1 (Int -> (a,Int))
> mkT1 :: a -> T1 a
> mkT1 a = T1 (\x -> (a, x))
> data T2 a = T2 (Int -> (a,Int))
> mkT2 :: a -> T2 a
> mkT2 a = T2 (\x -> (a, x))
> makeT a b = mkT a b
> --makeT1 a b = mkT1 a b
> --makeT2 a b = mkT2 a b
> why makeT 1 2 works while makeT1 a makeT2 will not compile?
> That is to say: why mkT1 and mkT2 cannot be used (even though the
> compiler does not complain)?
> That is to say, can someone explain this behaviour? I do not grasp it.
Because T a is a function type, namely Int -> (a,Int), so
if a has type ta, mkT a has type Int -> (ta,Int) and so can be applied to a
makeT a b = (mkT a) b
is fine. However, neither T1 a nor T2 a is a function type, a value of type
T1 a is a function _wrapped by the data (or value) constructor T1_ (the same
applies to T2, of course), so before you can apply mkT1 a to an Int, you have
to unwrap it:
unT1 :: T1 a -> T a
unT1 (T1 f) = f
makeT1 a b = unT1 (mkT1 a) b
will work fine.
> Thanks for your kind attention.
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
"In My Egotistical Opinion, most people's C programs should be
indented six feet downward and covered with dirt."
-- Blair P. Houghton
More information about the Haskell-Cafe