在球拍中编写解析器时出现类型检查器问题

时间:2019-05-04 16:01:05

标签: parsing racket typed-racket

我有一种语言PLANG,可以评估 点(数字)序列上的多项式。  该语言允许 形式{{…} {…}},其中所有和所有 有效的AE表达式(且≥1和ℓ≥1)。

我试图为此语言编写一个解析,这是我到目前为止所掌握的:

(define-type PLANG
  [Poly (Listof AE) (Listof AE)])
 (define-type AE
 [Num Number]
 [Add AE AE]
 [Sub AE AE]
 [Mul AE AE]
 [Div AE AE])

 (: parse-sexpr : Sexpr -> AE)
 ;; to convert s-expressions into AEs
 (define (parse-sexpr sexpr)
 (match sexpr
 [(number: n) (Num n)]
 [(list '+ lhs rhs) (Add (parse-sexpr lhs)
 (parse-sexpr rhs))]
 [(list '- lhs rhs) (Sub (parse-sexpr lhs)
 (parse-sexpr rhs))]
 [(list '* lhs rhs) (Mul (parse-sexpr lhs)
 (parse-sexpr rhs))]
 [(list '/ lhs rhs) (Div (parse-sexpr lhs)
 (parse-sexpr rhs))]
[else (error 'parse-sexpr "bad syntax in ~s"
 sexpr)]))

 (: parse : String -> PLANG)
 ;; parses a string containing a PLANG expression to a PLANG AST

 (define (parse str)
 (let ([code (string->sexpr str)])
 (parse-sexpr (code) )))



(test (parse "{{poly 1 2 3} {1 2 3}}")
 => (Poly (list (Num 1) (Num 2) (Num 3))
 (list (Num 1) (Num 2) (Num 3))))
(test (parse "{{poly } {1 2} }") 
 =error> "parse: at least one coefficient is
 required in ((poly) (1 2))")
(test (parse "{{poly 1 2} {} }")
 =error> "parse: at least one point is
 required in ((poly 1 2) ())")

当我试图使其运行时,出现错误:

Type Checker: Cannot apply expression of type (U (Listof Sexpr) Boolean Real String Symbol), since it is not a function type in: (code)
. Type Checker: type mismatch
  expected: Poly
  given: AE in: (parse-sexpr (code))
. Type Checker: Summary: 2 errors encountered in:
  (code)
  (parse-sexpr (code))
> 

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

第一个问题是由一对多余的括号引起的。请记住,在球拍,类型球拍和#lang pl中,括号通常表示函数应用程序,如下所示:

(function argument ...)

因此,当您编写(code)时,它将尝试将code解释为一个函数,并使用零个参数进行调用。

您可以通过在(code)函数主体中将code替换为parse来解决此问题。

(define (parse str)
  (let ([code (string->sexpr str)])
    (parse-sexpr code)))

发生第二个问题是因为您指定了parse函数应返回一个PLANG,但它返回了一个返回parse-sexpr的结果AE

另一种措辞是,您为AE实现了解析,但没有为PLANG实现解析。