Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

function - Haskell parsing prefix evaluation

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...