[Haskell-beginners] Making a generic interpreter
Erik Helin
erik.helin at gmail.com
Fri May 6 19:39:13 CEST 2011
Hi Patrick,
thanks for taking your time!
On Fri, May 6, 2011 at 18:45, Patrick LeBoutillier
<patrick.leboutillier at gmail.com> wrote:
> I don't see how you can make the StackBool something else than Bool.
> The CMP and BRANCH operators seem to me very Boolean by definition.
> Can you provide an example of how it would work?
>
> Patrick
>
I actually can :) I've been hacking today, and the result is:
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
class (Show a) => AbsInteger a b | a -> b where
(+) :: a -> a -> a
(==) :: a -> a -> b
absInteger :: Integer -> a
class (Show a) => AbsBool a where
cond :: a -> [Code] -> [Code] -> [Code]
absBool :: Bool -> a
instance AbsBool Bool where
cond b c1 c2 = if b then c1 else c2
absBool b = b
instance AbsInteger Integer Bool where
a + b = (Prelude.+) a b
a == b = (Prelude.==) a b
absInteger a = a
Now, if I would like to use my own integer type or my own bool type, I can do:
data MyInteger = MyInteger Integer deriving (Show)
data MyBool = MyBool Bool deriving (Show)
instance AbsBool MyBool where
cond (MyBool b) c1 c2 = if b then c1 else c2
absBool b = MyBool b
instance AbsInteger MyInteger MyBool where
(MyInteger a) + (MyInteger b) = MyInteger $ (Prelude.+) a b
(MyInteger a) + (MyInteger b) = MyBool $ (Prelude.==) a b
absInteger a = MyInteger a
The eval function has to be tweaked a little bit, but it is almost
plug'n'play :)
However, due to the functional dependency of AbsInteger, this does not
allow me to use
MyInteger and Bool, since there can only be one pair of an integer
type and a bool type, and Integer and Bool are already instantiating
AbsInteger .
Do you know some of way of making it possible to have several integer
type and boolean type pairs instantiating the class AbsInteger?
More information about the Beginners
mailing list