0

我收到了这个错误,我不知道我做错了什么。我是 Haskell 的新手,所以请为我详细说明一切。

import Data.Maybe

data Op = Add | Sub | Mul | Div | And | Or | Not | Eq | Less | Great
    deriving (Eq, Show)

data Exp = Literal Value
     | Primitive Op [Exp]
     | Variable String
     | If Exp Exp Exp
     | Let [(String, Exp)] Exp
    deriving (Show, Eq)

data Value = Number Int
       | Bool Bool
       | String String
    deriving (Eq, Show)

type Env = [(String, Value)]

eval :: Env -> Exp -> Value
eval e (Literal v) = v
eval e (Variable x) = fromJust (lookup x e)   --22

prim :: Op -> [Value] -> Value
prim Add [Number a, Number b] = Number (a + b)
prim And [Bool a, Bool b] = Bool (a && b)
prim Sub [Number a, Number b] = Number (a - b)
prim Mul [Number a, Number b] = Number (a * b)
prim Div [Number a, Number b] = Number (a `div` b)
prim Or [Bool a, Bool b] = Bool (a || b)
prim Not [Bool a] = Bool (not a)
prim Eq [Number a, Number b] = Bool (a == b)
prim Eq [String a, String b] = Bool (a == b) 
prim Less [Number a, Number b] = Bool (a < b)
prim Less [String a, String b] = Bool (a < b)
prim Great [Number a, Number b] = Bool (a > b)
prim Great [String a, String b] = Bool (a > b) --37

main = do
    n = "n"    -- parse error on input `='
    nv = Variable "n"   -- parse error on input `='
    lit n = Literal (Number n)  

    t0 = Primitive Mul [lit 5, lit 2]    
    t1 = Let [(n, t0)] (If (Primitive Great [nv, lit 9]) (lit 1) (lit 0))  -- parse error on input `='

我在收到错误的评论中写道。我检查了参数的有效性,一切看起来都很好。这可能是我的语法错误......我猜。

先感谢您。

4

1 回答 1

4

您的主要功能几乎在所有方面都被破坏了。您是否学习过 monad 或者对于这种情况仅了解 IO monad?

main :: IO Exp
main = do   
  let n = "n"
      nv = Variable "n"
      lit n = Literal (Number n)
      t0 = Primitive Mul [lit 5, lit 2]
      in return $ Let [(n, t0)] (If (Primitive Great [nv, lit 9]) (lit 1) (lit 0))

您不能只=在该 do-Block 的上下文中使用。此版本按预期工作。了解let表达式和return. 如果您不知道这一点,请在此处阅读示例。

于 2013-02-02T02:02:13.747 回答