今天早些时候我遇到了 F# 引用的限制,在这里问了一个问题:F# 引用:变量可能会超出范围
现在,在将http://www.cs.rice.edu/~taha/publications/journal/dspg04a.pdf中出现的示例从 MetaOcaml 转换为 F#时,我可能遇到了另一个限制。
这次我有这个 MetaOcaml 片段:
let rec peval2 p env fenv=
match p with
Program ([],e) -> eval2 e env fenv
| Program (Declaration (s1,s2,e1)::tl,e) ->
.<let rec f x = .~(eval2 e1 (ext env s2 .<x>.)
(ext fenv s1 .<f>.))
in .~(peval2 (Program(tl,e)) env (ext fenv s1 .<f>.))>.
我把它转换成
let rec peval2 p env fenv =
match p with
| Program ([], e) -> eval2 e env fenv
| Program (Declaration (s1, s2, e1) :: tl, e) ->
<@ let rec f x = %(eval2 e1 (ext env s2 <@ x @>)
(ext fenv s1 <@ f @>))
in %(peval2 (Program(tl, e)) env (ext fenv s1 <@ f @>)) @>
我收到以下编译时错误:This expression was expected to have type int -> Expr<int> but here has type Expr<'a>
使用两个<@ f @>
.
直觉上,我认为这个错误很有意义。但是在这种情况下,F# 中有没有办法描述我想要的东西?
代码示例:
open Microsoft.FSharp.Quotations
type Exp =
| Int of int
| Var of string
| App of string * Exp
| Add of Exp * Exp
| Sub of Exp * Exp
| Mul of Exp * Exp
| Div of Exp * Exp
| Ifz of Exp * Exp * Exp
type Def = Declaration of string * string * Exp
type Prog = Program of Def list * Exp
exception Yikes
let env0 = fun x -> raise Yikes
let fenv0 = env0
let ext env x v = fun y -> if x = y then v else env y
let rec eval2 e env fenv =
match e with
| Int i -> <@ i @>
| Var s -> env s
| App (s, e2) -> <@ %(fenv s) %(eval2 e2 env fenv) @>
| Add (e1, e2) -> <@ %(eval2 e1 env fenv) + %(eval2 e2 env fenv) @>
| Sub (e1, e2) -> <@ %(eval2 e1 env fenv) - %(eval2 e2 env fenv) @>
| Mul (e1, e2) -> <@ %(eval2 e1 env fenv) * %(eval2 e2 env fenv) @>
| Div (e1, e2) -> <@ %(eval2 e1 env fenv) / %(eval2 e2 env fenv) @>
| Ifz (e1, e2, e3) -> <@ if %(eval2 e1 env fenv) = 0
then %(eval2 e2 env fenv)
else %(eval2 e3 env fenv) @>
let rec peval2 p env fenv =
match p with
| Program ([], e) -> eval2 e env fenv
| Program (Declaration (s1, s2, e1) :: tl, e) ->
<@ let rec f x = %(eval2 e1 (ext env s2 <@ x @>)
(ext fenv s1 <@ f @>))
in %(peval2 (Program(tl, e)) env (ext fenv s1 <@ f @>)) @>