简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM