0

我正在处理任务。我不知道为什么会收到此错误。

我通过注释指出了错误来自的行。

如果你可以(你不必),我认为我的funccall功能不起作用。

import Data.Maybe 

data Operator = Add | Sub | Mul | Div | And | Or | Not | Eq | Less | Great
  deriving (Eq, Show)
data Expression = Lit Value
         | Prim Operator [Expression]
         | Variable String
         | If Expression Expression Expression
         | Let [(String, Expression)] Expression
     | Func [String] Expression
     | Call Expression [Expression]
  deriving (Show, Eq)

data Value = Num Int
           | Bool Bool
       | Closure [String] Expression Environment
  deriving (Eq, Show)

type Environment = [(String, Value)]
--20
prim :: Operator -> [Value] -> Value
prim Add [Num a, Num b] = Num (a+b)
prim Mul [Num a, Num b] = Num (a*b)
prim Sub [Num a, Num b] = Num (a-b)
prim Div [Num a, Num b] = Num (a `div` b)
prim And [Bool a, Bool b] = Bool (a && b)
prim Or [Bool a, Bool b] = Bool (a || b)
prim Not [Bool a] = Bool (not a)
prim Eq [a, b] = Bool (a == b)
prim Less [Num a, Num b] = Bool (a < b)
prim Great [Num a, Num b] = Bool (a > b)
--32
evaluate :: Environment -> Expression -> Value
evaluate e (Lit v)  = v
evaluate e (Prim op as) = prim op (map (evaluate e) as)
evaluate e (Variable x) = fromJust (lookup x e)
evaluate e (If a b c)   = evaluate e (if fromBool (evaluate e a) then b else c)
evaluate e (Let bs b)   = evaluate ([(x, evaluate e d) | (x,d) <- bs ] ++ e) b

eval e (Func str ex) = (Closure str ex e) --40
evaluate e (Call ex exl) = let (Closure a b c) = (evaluate e ex) 
            in (Closure a b (c ++ (helper a (map (evaluate e) exl)))) 

helper :: [String] -> [Expression] -> [(String, Expression)]
helper (a:ar) (b:br) = (a, b) : helper ar br 

fromBool (Bool b) = b
--48
main = do
  let m = "m"
      k = Variable "k"  -- parse error on input `='
      y = Variable "y"
      lit m = Lit (Num m)
      a0 = Func [“k”] (Prim Mul [k, lit 2))
      in return $ Let [(“y”, a0)] (Prim Add [Call y [lit 3], Call y [lit 10]]) 
-- This is basically Let y = func(k) k*2 in y(3) + y(10) which returns 26.
4

1 回答 1

5
  • 第 40 行eval应该是,evaluate否则您将evaluate使用一些单独的、不相关的函数来分解函数的定义eval

  • 第 54、55 行。您正在使用一些 unicode 定向引号,但应该使用 ASCii "

  • 第 54 行,在需要方括号 ']' 时使用 ')'。

  • helper类型不正确,其类型会破坏抽象。为了使其正确,您应该更改ExpressionValue,但为了保持您的抽象,您应该将结果设置为Environment.

编辑:

正如我所说,我将助手的类型签名更改为:

helper :: [String] -> [Value] -> [(String, Value)]

编辑2:

评论您编辑的代码。您在第 55 行意外删除了左括号:

Let ["y", a0)]  -- should be Let [("y", a0)]

在那之前的那一行,你试图修复一个有语法错误的列表[ ... ),但是你改变了错误的括号,导致( ...)而不是正确的[...]

具体来说:

[k, lit 2]
于 2013-02-13T02:55:09.210 回答