gpt4 book ai didi

Coq最佳实践: mutual recursion,只有一个函数在结构上减少

转载 作者:行者123 更新时间:2023-12-01 17:54:28 26 4
gpt4 key购买 nike

考虑以下无类型 lambda 演算的玩具表示:

Require Import String.
Open Scope string_scope.

Inductive term : Set :=
| Var : string -> term
| Abs : string -> term -> term
| App : term -> term -> term.

Fixpoint print (term : term) :=
match term return string with
| Var id => id
| Abs id term => "\" ++ id ++ " " ++ print term
| App term1 term2 => print_inner term1 ++ " " ++ print_inner term2
end
with print_inner (term : term) :=
match term return string with
| Var id => id
| term => "(" ++ print term ++ ")"
end.

类型检查 print 失败并出现以下错误:

Recursive definition of print_inner is ill-formed.
[...]
Recursive call to print has principal argument equal to "term" instead of "t".

实现此目的最可读/符合人体工程学/最有效的方法是什么?

最佳答案

您可以使用嵌套递归函数:

Fixpoint print (tm : term) : string :=
match tm return string with
| Var id => id
| Abs id body => "\" ++ id ++ ". " ++ print body
| App tm1 tm2 =>
let fix print_inner (tm : term) : string :=
match tm return string with
| Var id => id
| _ => "(" ++ print tm ++ ")"
end
in
print_inner tm1 ++ " " ++ print_inner tm2
end.

这种方法可以扩展到处理 pretty-print ——通常的约定是不打印 x y z 等表达式中的括号(应用程序与左侧关联)或打印 \x。\y。 x y\xy。 x y :

Definition in_parens (stm : string) : string := "(" ++ stm ++ ")".

Fixpoint pprint (tm : term) : string :=
match tm with
| Var id => id
| Abs id tm1 =>
let fix pprint_nested_abs (tm : term) : string :=
match tm with
| Abs id tm1 => id ++ pprint_nested_abs tm1
| _ => ". " ++ pprint tm
end
in
"\" ++ id ++ pprint_nested_abs tm1

(* e.g. (\x. x x) (\x. x x) *)
| App ((Abs _ _) as tm1) ((Abs _ _) as tm2) =>
in_parens (pprint tm1) ++ " " ++ in_parens (pprint tm2)

(* variable scopes *)
| App ((Abs _ _) as tm1) tm2 => in_parens (pprint tm1) ++ " " ++ pprint tm2

(* `x \x. x` looks ugly, `x (\x. x)` is better; also handle `x (y z)` *)
| App tm1 ((Abs _ _) as tm2) | App tm1 (App _ _ as tm2) =>
pprint tm1 ++ " " ++ in_parens (pprint tm2)

| App tm1 tm2 => pprint tm1 ++ " " ++ pprint tm2
end.

顺便说一句,CPDT有some material关于相互递归与嵌套递归,但在不同的设置中。

关于Coq最佳实践: mutual recursion,只有一个函数在结构上减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44792791/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com