如何在 F# 中实现 beta 缩减函数?

发布于 2024-09-29 15:46:22 字数 262 浏览 1 评论 0原文

我正在用 F# 编写 lambda 演算,但我一直坚持实现 beta 约简(用实际参数替换形式参数)。

(lambda x.e)f
--> e[f/x]

使用示例:

(lambda n. n*2+3) 7
--> (n*2+3)[7/n]
--> 7*2+3

所以我很想听到一些关于其他人如何解决这个问题的建议。任何想法将不胜感激。

谢谢!

I am writing a lambda calculus in F#, but I am stuck on implementing the beta-reduction (substituting formal parameters with the actual parameters).

(lambda x.e)f
--> e[f/x]

example of usage:

(lambda n. n*2+3) 7
--> (n*2+3)[7/n]
--> 7*2+3

So I'd love to hear some suggestions in regards to how others might go about this. Any ideas would be greatly appreciated.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傻比既视感 2024-10-06 15:46:22

假设您的表达式表示形式类似于

type expression = App of expression * expression
                | Lambda of ident * expression
                (* ... *)

,您有一个函数 subst (x:ident) (e1:expression) (e2:expression) : expression ,它替换所有出现的 x 与 e2 中的 e1,并且您想要正常的顺序评估,您的代码应如下所示:

let rec eval exp =
  match exp with
  (* ... *)
  | App (f, arg) -> match eval f with Lambda (x,e) -> eval (subst x arg e)

subst 函数应按如下方式工作:

对于函数应用程序,它应该在两个子表达式上递归地调用自身。

对于 lambda,它应该在 lambda 的主体表达式上调用自身,除非 lambda 的参数名称等于您要替换的标识符(在这种情况下,您可以保留 lambda,因为标识符不会出现自由地在其内部的任何地方)。

对于变量,它应该返回未更改的变量或替换表达式,具体取决于变量的名称是否等于标识符。

Assuming your representation of an expression looks like

type expression = App of expression * expression
                | Lambda of ident * expression
                (* ... *)

, you have a function subst (x:ident) (e1:expression) (e2:expression) : expression which replaces all free occurrences of x with e1 in e2, and you want normal order evaluation, your code should look something like this:

let rec eval exp =
  match exp with
  (* ... *)
  | App (f, arg) -> match eval f with Lambda (x,e) -> eval (subst x arg e)

The subst function should work as follows:

For a function application it should call itself recursively on both subexpressions.

For lambdas it should call itself on the lambda's body expression unless the lambda's argument name is equal to the identifier you want to replace (in which case you can just leave the lambda be because the identifier can't appear freely anywhere inside it).

For a variable it should either return the variable unchanged or the replacement-expression depending on whether the variable's name is equal to the identifier.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文