user20556088
user20556088

Reputation: 29

Haskell Error: Variable not in scope: guard :: Bool -> Maybe a0

whats kind of Error is this?

error:Variable not in scope: guard :: Bool -> Maybe a0

thats the Code

eval3 :: Exp -> Maybe Integer
eval3 e =
  case e of
    (Const x) -> pure x
    (ExpAdd x y) -> eval3 x >>= \x' -> eval3 y >>= \y' -> return (x'+y')
    (ExpMult x y) -> eval3 x >>= \x' -> eval3 y >>= \y' -> return (x'*y')
    (ExpDiv x y) -> eval3 x >>= \x' -> eval3 y >>= (\y' -> guard (y'/=0) >> return (div x'y'))

Upvotes: 1

Views: 135

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

As @SilvioMoyolo says, you need to import Control.Monad. Howeve, using guard looks a bit like overkill here, you can work with a guard instead. For the ExpAdd and ExpMult, you can use liftA2:

import Control.Applicative(liftA2)
import Data.Function(on)

eval3 :: Exp -> Maybe Integer
eval3 (Const x) = pure x
eval3 (ExpAdd x y) = (liftA2 (+) `on` eval3) x y
eval3 (ExpMult x y) = (liftA2 (*) `on` eval3) x y
eval3 (ExpDiv x y)
  | Just x' <- eval3 x, Just y' <- eval3 y, y' /= 0 = pure (div x' y')
  | otherwise = Nothing

Upvotes: 1

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

guard is in Control.Monad, not Prelude. You just need to import Control.Monad at the top of your file.

Upvotes: 5

Related Questions