[Haskell-beginners] Making a generic interpreter

Daniel Fischer daniel.is.fischer at googlemail.com
Sat May 7 12:24:34 CEST 2011


On Saturday 07 May 2011 11:39:44, Erik Helin wrote:
> Thank you Patrick for posting your code, it helps a lot too see a
> complete example!
> 
> On Sat, May 7, 2011 at 03:11, Patrick LeBoutillier
> 
> <patrick.leboutillier at gmail.com> wrote:
> > instance AbsInteger Integer where
> >   a `add` b = (+) a b
> >   a `eq` b = absBool $ a == b
> >   absInteger a = a
> 
> In my code, I did not use "a `eq` b = absBool $ a == b". Instead, I
> used "a `eq` b = a == b".
> I thought, since "a == b" is of type Bool, and Bool is an instance of
> AbsBool, I can just return type Bool.
> 
> Why isn't this the case? What is it about typeclasses that I'm not
> understanding?

A type signature

foo :: (Bar b) => SomeType -> b

says "given a value of SomeType, I can produce return values of *any* type, 
as long as it's an instance of Bar".
The caller decides which type it wants and the callee must be able to 
produce it.

In OO, on the other hand, the callee decides which type it returns, a 
signature

Bar foo(SomeType s);

(where Bar is an interface) says foo will return values of a type, all you 
know about which is that it implements Bar.

Using explicit quantification, the Haskell type is

foo :: forall b. (Bar b) => SomeType -> b

while the OO-type would correspond to

foo :: exists b. (Bar b) => SomeType -> b

(the latter type doesn't exist in Haskell).



More information about the Beginners mailing list