Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
160 views
Welcome To Ask or Share your Answers For Others

1 Answer

The error message says that the data constructor N is not in scope. Data constructors are the things on the right-hand side of data statements. In your example, V, Neg, A, and M are data constructors. "Not in scope" means "not defined where it was used".

It looks like you wrote N where you meant to write Neg, or vice versa. Fixing your data statement to read:

data Ast = V Int | N Ast | A Ast Ast | M Ast Ast deriving (Show,Eq)

allows the program to compile.

There are still a few bugs in the program. For example, the following gets stuck in a loop:

> parseE (words "* + 1 2 * 3 + 7 - 2")
(M (A (V 1) (V 2)) (M (V 3) (A (V 7) (N  -- freezes

because of the statement:

let (a,r) = parseE r in (N a, r)

which introduces an unintended recursive definition -- you're defining r as the result of calling parseE r, which causes an infinite loop. You have a similar problem in the case that tries to handle parentheses.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...