Reputation: 287
I have this function which calculates the add
data Expr
= Num Double
| Add Expr Expr
| Sub Expr Expr
deriving (Show)
eval :: Expr -> Maybe Double
eval (Num a) = if a < 0 then
eval (Add a b) = case eval a
Nothing -> Nothing
Just a1 -> case eval b of
Nothing -> Nothing
Just b1 -> Just (a1 + b1)
while calling it like this, it returns error:
eval Add (Expr(1), Expr(2))
:30:20: error: Data constructor not in scope: Expr :: t1 -> b0
Upvotes: 1
Views: 229
Reputation: 476557
Your Add (Expr(1), Expr(2))
is not an expression for an Expr
. First of all you need Num
to construct an Expr
, not an Expr
since that is a type constructor, not a data constructor:
Add (Num 1) (Num 2)
Furthermore there should be no comma between the two, and we need brackets to pass the entire Expr
we need parenthesis around the entire Add …
block, so:
eval (Add (Num 1) (Num 2))
In your eval
function it looks like something is missing after the if a < 0 then …
You can also implement eval (Add a b)
as:
eval :: Expr -> Maybe Double
eval (Num a) = if a < 0 then … else …
eval (Add a b) = (+) <$> eval a <*> eval b
Upvotes: 6