I'm struggling with this code.
import Data.Char (isDigit)
data Ast = V Int | Neg Ast | A Ast Ast | M Ast Ast deriving (Show,Eq)
parseE ("+":xs) = let (e1,r1) = parseE xs; (e2,r2) = parseE r1 in (A e1 e2, r2)
parseE ("*":xs) = let (e1,r1) = parseE xs; (e2,r2) = parseE r1 in (M e1 e2, r2)
parseE ("-":xs) = let (a,r) = parseE r in (N a, r)
parseE ("(":xs) = let (a,")":r) = parseE r in (a,r)
parseE (x:xs) = (V (read x :: Int), xs)
eval xs = parseE xs
When my input is something like: * + 1 2 * 3 + 7 - 2
I want the ouput to be: ((1+2)*3)*(3*(7-2))
which should show 45
When I load my file in haskell, I get this error :
:load "newf.hs"
[1 of 1] Compiling Main ( newf.hs, interpreted )
newf.hs:6:44: error: Data constructor not in scope: N :: Ast -> Ast
|
6 | parseE ("-":xs) = let (a,r) = parseE r in (N a, r)
| ^
Failed, 0 modules loaded.
The error message says that the data constructor
N
is not in scope. Data constructors are the things on the right-hand side ofdata
statements. In your example,V
,Neg
,A
, andM
are data constructors. "Not in scope" means "not defined where it was used".It looks like you wrote
N
where you meant to writeNeg
, or vice versa. Fixing yourdata
statement to read:allows the program to compile.
There are still a few bugs in the program. For example, the following gets stuck in a loop:
because of the statement:
which introduces an unintended recursive definition -- you're defining
r
as the result of callingparseE r
, which causes an infinite loop. You have a similar problem in the case that tries to handle parentheses.