Search code examples
haskelltypestype-mismatch

Haskell: can't match expected type Either


I have the following code, where I try to have the function eval3 return an Int or Bool, but I get an error message:

• Couldn't match expected type ‘Either Int Bool’
              with actual type ‘Int’

• In the expression: eval e2

  In the expression: if eval0 e1 then eval e2 else eval0 e3

  In an equation for ‘eval3’:

      eval3 (If e1 e2 e3) = if eval0 e1 then eval e2 else eval0 e3

error:

• Couldn't match expected type ‘Either Int Bool’
              with actual type ‘Bool’

• In the expression: eval0 e3

  In the expression: if eval0 e1 then eval e2 else eval0 e3

  In an equation for ‘eval3’:

      eval3 (If e1 e2 e3) = if eval0 e1 then eval e2 else eval0 e3


{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}

data Exp = V Var
    | B Bool
    | L Exp
    | A Exp Exp
    | MyInt Int
    | And Exp Exp
    | If Exp Exp Exp
data Var = VZ |VS Var

eval :: Exp -> Int
eval (MyInt e1)     = e1

eval0 :: Exp -> Bool
eval0 (B e1) = e1


eval3 :: Exp -> Either Int Bool
eval3 (If e1 e2 e3) = if eval0 e1 then eval e2 else eval0 e3

What do I need to add or change to get the function eval3 to return either type


Solution

  • We do not return either type, but rather the Either type.

    To construct a value of type Either Int Bool either use Left i where i :: Int or Right b where b :: Bool. In your case,

    eval3 :: Exp -> Either Int Bool
    eval3 (If e1 e2 e3) = if eval0 e1 then Left (eval e2) else Right (eval0 e3)
    

    since you have

    eval :: Exp -> Int       -- eval (e2 :: Exp) :: Int
    
    eval0 :: Exp -> Bool     -- eval0 (e3 :: Exp) :: Bool