From 83d8006a7cc3d5429bb5e2d0abcb3da7ea4a9035 Mon Sep 17 00:00:00 2001 From: zihang Date: Wed, 4 Dec 2024 11:20:42 +0800 Subject: [PATCH] doc(example): extract code for lambda --- next/locales/zh_CN/LC_MESSAGES/tutorial.po | 136 ++++++------ next/sources/lambda-expression/.gitignore | 2 + next/sources/lambda-expression/LICENSE | 202 ++++++++++++++++++ next/sources/lambda-expression/README.md | 3 + next/sources/lambda-expression/moon.mod.json | 10 + .../lambda-expression/src/moon.pkg.json | 1 + next/sources/lambda-expression/src/top.mbt | 120 +++++++++++ next/tutorial/example/lambda/index.md | 162 +++++--------- 8 files changed, 453 insertions(+), 183 deletions(-) create mode 100644 next/sources/lambda-expression/.gitignore create mode 100644 next/sources/lambda-expression/LICENSE create mode 100644 next/sources/lambda-expression/README.md create mode 100644 next/sources/lambda-expression/moon.mod.json create mode 100644 next/sources/lambda-expression/src/moon.pkg.json create mode 100644 next/sources/lambda-expression/src/top.mbt diff --git a/next/locales/zh_CN/LC_MESSAGES/tutorial.po b/next/locales/zh_CN/LC_MESSAGES/tutorial.po index 7244da76..a074b75b 100644 --- a/next/locales/zh_CN/LC_MESSAGES/tutorial.po +++ b/next/locales/zh_CN/LC_MESSAGES/tutorial.po @@ -9,7 +9,7 @@ msgid "" msgstr "" "Project-Id-Version: MoonBit Document \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-12-03 16:21+0800\n" +"POT-Creation-Date: 2024-12-04 11:18+0800\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language: zh_CN\n" @@ -2614,18 +2614,18 @@ msgid "" "}\n" msgstr "" -#: ../../tutorial/example/lambda/index.md:27 +#: ../../tutorial/example/lambda/index.md:25 msgid "" "Concepts encountered in daily programming such as boolean values, if " "expressions, natural number arithmetic, and even recursion can all be " "implemented using Lambda expressions. However, this is not the focus of " -"this article. Interested readers can refer to:" +"this article." msgstr "" -#: ../../tutorial/example/lambda/index.md:29 +#: ../../tutorial/example/lambda/index.md:28 msgid "" -"Programming with Nothing:[https://tomstu.art/programming-with-" -"nothing](https://tomstu.art/programming-with-nothing)" +"Interested readers can refer to: [Programming with " +"Nothing](https://tomstu.art/programming-with-nothing)" msgstr "" #: ../../tutorial/example/lambda/index.md:31 @@ -2711,7 +2711,7 @@ msgid "" "variables:" msgstr "" -#: ../../tutorial/example/lambda/index.md:67 +#: ../../tutorial/example/lambda/index.md:69 msgid "" "// (λx.E) T => E.subst(x, T)\n" "fn subst(self : Term, var : String, term : Term) -> Term {\n" @@ -2731,31 +2731,31 @@ msgid "" "}\n" msgstr "" -#: ../../tutorial/example/lambda/index.md:86 +#: ../../tutorial/example/lambda/index.md:88 msgid "" "Next, I'll introduce a less popular but somewhat convenient method: de " "Bruijn index." msgstr "" -#: ../../tutorial/example/lambda/index.md:88 +#: ../../tutorial/example/lambda/index.md:90 msgid "De Bruijn Index" msgstr "" -#: ../../tutorial/example/lambda/index.md:90 +#: ../../tutorial/example/lambda/index.md:92 msgid "" "De Bruijn index is a technique for representing variables in Lambda terms" " using integers. Specifically, it replaces specific variables with " "Lambdas between the variable and its original imported position." msgstr "" -#: ../../tutorial/example/lambda/index.md:92 +#: ../../tutorial/example/lambda/index.md:94 msgid "" "λx.(λy.x (λz.z z))\n" "\n" "λ.(λ.1 (λ.0 0))\n" msgstr "" -#: ../../tutorial/example/lambda/index.md:98 +#: ../../tutorial/example/lambda/index.md:100 msgid "" "In the example above, there is one Lambda `λy` between the variable `x` " "and its introduction position `λx`, so `x` is replaced with `1`. For " @@ -2766,19 +2766,19 @@ msgid "" " by the number of nested Lambdas." msgstr "" -#: ../../tutorial/example/lambda/index.md:100 +#: ../../tutorial/example/lambda/index.md:102 msgid "" "The same variable may be replaced with different integers in different " "positions." msgstr "" -#: ../../tutorial/example/lambda/index.md:102 +#: ../../tutorial/example/lambda/index.md:104 msgid "" "We define a new type `TermDBI` to represent Lambda terms using de Bruijn " "indices:" msgstr "" -#: ../../tutorial/example/lambda/index.md:104 +#: ../../tutorial/example/lambda/index.md:106 msgid "" "enum TermDBI {\n" " Var(String, Int)\n" @@ -2793,22 +2793,22 @@ msgid "" "form is painful, so we need to write a function `bruijn()` to convert " "`Term` to `TermDBI`. This is also why there is still a `String` in the " "definition of the `TermDBI` type, so that the original variable name can " -"be used for its `to_string` method, making it easy to print and view the " -"evaluation results with `println`." +"be used for its `Show` implementation, making it easy to print and view " +"the evaluation results with `println`." msgstr "" #: ../../tutorial/example/lambda/index.md:114 msgid "" -"fn to_string(self : TermDBI) -> String {\n" +"impl Show for TermDBI with output(self : TermDBI, logger) -> Unit {\n" " match self {\n" -" Var(name, _) => name\n" -" Abs(name, body) => \"(\\\\\\{name}.\\{body})\"\n" -" App(t1, t2) => \"\\{t1} \\{t2}\"\n" +" Var(name, _) => logger.write_string(name)\n" +" Abs(name, body) => logger.write_string(\"(\\\\\\{name}.\\{body})\")\n" +" App(t1, t2) => logger.write_string(\"\\{t1} \\{t2}\")\n" " }\n" "}\n" msgstr "" -#: ../../tutorial/example/lambda/index.md:124 +#: ../../tutorial/example/lambda/index.md:121 msgid "" "To simplify implementation, if the input `Term` contains free variables, " "the `bruijn()` function will report an error directly. MoonBit provides a" @@ -2817,21 +2817,21 @@ msgid "" "respectively." msgstr "" -#: ../../tutorial/example/lambda/index.md:126 +#: ../../tutorial/example/lambda/index.md:123 msgid "Readers familiar with Rust should find this familiar." msgstr "" -#: ../../tutorial/example/lambda/index.md:128 +#: ../../tutorial/example/lambda/index.md:126 msgid "fn bruijn(self : Term) -> Result[TermDBI, String]\n" msgstr "" -#: ../../tutorial/example/lambda/index.md:132 +#: ../../tutorial/example/lambda/index.md:130 msgid "" "We take a clumsy approach to save variable names and their associated " "nesting depth. First, we define the `Index` type:" msgstr "" -#: ../../tutorial/example/lambda/index.md:134 +#: ../../tutorial/example/lambda/index.md:132 msgid "" "struct Index {\n" " name : String\n" @@ -2839,41 +2839,41 @@ msgid "" "}\n" msgstr "" -#: ../../tutorial/example/lambda/index.md:141 +#: ../../tutorial/example/lambda/index.md:138 msgid "" "Then we write a helper function to find the corresponding `depth` based " "on a specific `name` from `List[Index]`:" msgstr "" -#: ../../tutorial/example/lambda/index.md:143 +#: ../../tutorial/example/lambda/index.md:140 msgid "" -"// Find the first depth corresponding to varname in the environment\n" +"// Find the depth corresponding to the first varname in the environment\n" "fn find(map : @immut/list.T[Index], varname : String) -> Result[Int, " "String] {\n" " match map {\n" -" Nil => Err(varname) // abort(\"variable '(varname)' not found\")\n" -" Cons(i, rest) => {\n" +" Nil => Err(varname)\n" +" Cons(i, rest) =>\n" " if i.name == varname {\n" " Ok(i.depth)\n" " } else {\n" " find(rest, varname)\n" " }\n" -" }\n" " }\n" "}\n" +"\n" msgstr "" -#: ../../tutorial/example/lambda/index.md:159 +#: ../../tutorial/example/lambda/index.md:147 msgid "Now we can complete the `bruijn()` function." msgstr "" -#: ../../tutorial/example/lambda/index.md:161 +#: ../../tutorial/example/lambda/index.md:149 msgid "" "Handling `Var` is the simplest, just look up the table to find the " "corresponding `depth`." msgstr "" -#: ../../tutorial/example/lambda/index.md:162 +#: ../../tutorial/example/lambda/index.md:150 msgid "" "`Abs` is a bit more complicated. First, add one to the `depth` of all " "`index` in the list (because the Lambda nesting depth has increased by " @@ -2881,13 +2881,13 @@ msgid "" "the list." msgstr "" -#: ../../tutorial/example/lambda/index.md:163 +#: ../../tutorial/example/lambda/index.md:151 msgid "" "`App` succeeds when both sub-items can be converted; otherwise, it " "returns an `Err`." msgstr "" -#: ../../tutorial/example/lambda/index.md:165 +#: ../../tutorial/example/lambda/index.md:153 msgid "" "fn go(m : @immut/list.T[Index], t : Term) -> Result[TermDBI, String] {\n" " match t {\n" @@ -2899,53 +2899,55 @@ msgid "" " }\n" " }\n" " Abs(varname, body) => {\n" -" let m = m.map(fn (index){\n" -" { name : index.name, depth : index.depth + 1 }\n" -" }).cons({ name : varname, depth : 0 })\n" +" let m = @immut/list.Cons(\n" +" { name: varname, depth: 0 },\n" +" m.map(fn(index) { { name: index.name, depth: index.depth + 1 } " +"}),\n" +" )\n" " let res = go(m, body)\n" " match res {\n" " Err(name) => Err(name)\n" " Ok(term) => Ok(Abs(varname, term))\n" " }\n" " }\n" -" App(e1, e2) => {\n" +" App(e1, e2) =>\n" " match (go(m, e1), go(m, e2)) {\n" " (Ok(e1), Ok(e2)) => Ok(App(e1, e2))\n" " (Err(name), _) => Err(name)\n" " (_, Err(name)) => Err(name)\n" " }\n" -" }\n" " }\n" "}\n" +"\n" "go(Nil, self)\n" msgstr "" -#: ../../tutorial/example/lambda/index.md:197 +#: ../../tutorial/example/lambda/index.md:160 msgid "Reduce on TermDBI" msgstr "" -#: ../../tutorial/example/lambda/index.md:199 +#: ../../tutorial/example/lambda/index.md:162 msgid "Reduction mainly deals with App, i.e., calls:" msgstr "" -#: ../../tutorial/example/lambda/index.md:201 +#: ../../tutorial/example/lambda/index.md:164 msgid "" "fn eval(self : TermDBI) -> TermDBI {\n" " match self {\n" -" App(t1, t2) => {\n" +" App(t1, t2) =>\n" " match (eval(t1), eval(t2)) {\n" " (Abs(_, t1), t2) => eval(subst(t1, t2))\n" " (t1, t2) => App(t1, t2)\n" " }\n" -" }\n" " Abs(_) => self\n" -" otherwise => abort(\"eval(): \\{otherwise} \")\n" -" // eval should not encounter free variables\n" +" // Eval should not encounter any free variables\n" +" _ => panic()\n" " }\n" "}\n" +"\n" msgstr "" -#: ../../tutorial/example/lambda/index.md:217 +#: ../../tutorial/example/lambda/index.md:170 msgid "" "First, attempt reduction on both sub-items, then see if `eval(t1)` " "results in a Lambda. If so, perform one step of variable substitution " @@ -2953,7 +2955,7 @@ msgid "" "(`Abs`), simply return them as they are." msgstr "" -#: ../../tutorial/example/lambda/index.md:219 +#: ../../tutorial/example/lambda/index.md:172 msgid "" "The implementation of the subst function becomes much simpler when we " "don't need to consider free variables. We just need to keep track of the " @@ -2961,41 +2963,35 @@ msgid "" "If they match, it's the variable to be replaced." msgstr "" -#: ../../tutorial/example/lambda/index.md:221 +#: ../../tutorial/example/lambda/index.md:174 msgid "" "fn subst(t1 : TermDBI, t2 : TermDBI) -> TermDBI {\n" " fn go(t1 : TermDBI, t2 : TermDBI, depth : Int) -> TermDBI {\n" " match t1 {\n" -" Var(name, d) => {\n" -" if d == depth {\n" -" t2\n" -" } else {\n" -" t1\n" -" }\n" -" }\n" -" Abs(name, t) => {\n" -" Abs(name, go(t, t2, depth + 1))\n" -" }\n" -" App(tl, tr) => {\n" -" App(go(tl, t2, depth), go(tr, t2, depth))\n" -" }\n" +" Var(_, d) => if d == depth { t2 } else { t1 }\n" +" Abs(name, t) => Abs(name, go(t, t2, depth + 1))\n" +" App(tl, tr) => App(go(tl, t2, depth), go(tr, t2, depth))\n" " }\n" " }\n" +"\n" " go(t1, t2, 0)\n" "}\n" +"\n" msgstr "" -#: ../../tutorial/example/lambda/index.md:244 +#: ../../tutorial/example/lambda/index.md:180 msgid "" -"The full code: " -"[try.moonbitlang.com/#b52b528b](https://try.moonbitlang.com/#b52b528b)" +"The full code: [GitHub repository](https://github.com/moonbitlang" +"/moonbit-docs/tree/main/next/sources/lambda-expression/src/top.mbt)" msgstr "" +"完整代码请查看 [GitHub 代码仓库](https://github.com/moonbitlang/moonbit-" +"docs/tree/main/next/sources/lambda-expression/src/top.mbt)。" -#: ../../tutorial/example/lambda/index.md:246 +#: ../../tutorial/example/lambda/index.md:182 msgid "Improvement" msgstr "" -#: ../../tutorial/example/lambda/index.md:248 +#: ../../tutorial/example/lambda/index.md:184 msgid "" "When mapping variable names to indices, we used the " "`@immut/list.T[Index]` type and updated the entire list every time we " diff --git a/next/sources/lambda-expression/.gitignore b/next/sources/lambda-expression/.gitignore new file mode 100644 index 00000000..b1283a74 --- /dev/null +++ b/next/sources/lambda-expression/.gitignore @@ -0,0 +1,2 @@ +target/ +.mooncakes/ diff --git a/next/sources/lambda-expression/LICENSE b/next/sources/lambda-expression/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/next/sources/lambda-expression/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/next/sources/lambda-expression/README.md b/next/sources/lambda-expression/README.md new file mode 100644 index 00000000..d89d85b2 --- /dev/null +++ b/next/sources/lambda-expression/README.md @@ -0,0 +1,3 @@ +# moonbit-community/lambda + +Check `tutorial/example/lambda`. \ No newline at end of file diff --git a/next/sources/lambda-expression/moon.mod.json b/next/sources/lambda-expression/moon.mod.json new file mode 100644 index 00000000..5f140707 --- /dev/null +++ b/next/sources/lambda-expression/moon.mod.json @@ -0,0 +1,10 @@ +{ + "name": "moonbit-community/lambda", + "version": "0.1.0", + "readme": "README.md", + "repository": "", + "license": "Apache-2.0", + "keywords": [], + "description": "", + "source": "src" +} \ No newline at end of file diff --git a/next/sources/lambda-expression/src/moon.pkg.json b/next/sources/lambda-expression/src/moon.pkg.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/next/sources/lambda-expression/src/moon.pkg.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/next/sources/lambda-expression/src/top.mbt b/next/sources/lambda-expression/src/top.mbt new file mode 100644 index 00000000..45f285e4 --- /dev/null +++ b/next/sources/lambda-expression/src/top.mbt @@ -0,0 +1,120 @@ +enum Term { + Var(String) // Variable + Abs(String, Term) // Define lambda, variables represented by strings + App(Term, Term) // Call lambda +} + +struct Index { + name : String + depth : Int +} + +enum TermDBI { + Var(String, Int) + Abs(String, TermDBI) + App(TermDBI, TermDBI) +} + +impl Show for TermDBI with output(self : TermDBI, logger) -> Unit { + match self { + Var(name, _) => logger.write_string(name) + Abs(name, body) => logger.write_string("(\\\{name}.\{body})") + App(t1, t2) => logger.write_string("\{t1} \{t2}") + } +} + +/// https://bor0.wordpress.com/2019/03/19/writing-a-lambda-calculus-evaluator-in-haskell/ +fn bruijn(self : Term) -> Result[TermDBI, String] { + // Find the depth corresponding to the first varname in the environment + fn find(map : @immut/list.T[Index], varname : String) -> Result[Int, String] { + match map { + Nil => Err(varname) + Cons(i, rest) => + if i.name == varname { + Ok(i.depth) + } else { + find(rest, varname) + } + } + } + + fn go(m : @immut/list.T[Index], t : Term) -> Result[TermDBI, String] { + match t { + Var(name) => { + let idx = find(m, name) + match idx { + Err(name) => Err(name) + Ok(idx) => Ok(Var(name, idx)) + } + } + Abs(varname, body) => { + let m = @immut/list.Cons( + { name: varname, depth: 0 }, + m.map(fn(index) { { name: index.name, depth: index.depth + 1 } }), + ) + let res = go(m, body) + match res { + Err(name) => Err(name) + Ok(term) => Ok(Abs(varname, term)) + } + } + App(e1, e2) => + match (go(m, e1), go(m, e2)) { + (Ok(e1), Ok(e2)) => Ok(App(e1, e2)) + (Err(name), _) => Err(name) + (_, Err(name)) => Err(name) + } + } + } + + go(Nil, self) +} + +fn subst(t1 : TermDBI, t2 : TermDBI) -> TermDBI { + fn go(t1 : TermDBI, t2 : TermDBI, depth : Int) -> TermDBI { + match t1 { + Var(_, d) => if d == depth { t2 } else { t1 } + Abs(name, t) => Abs(name, go(t, t2, depth + 1)) + App(tl, tr) => App(go(tl, t2, depth), go(tr, t2, depth)) + } + } + + go(t1, t2, 0) +} + +fn eval(self : TermDBI) -> TermDBI { + match self { + App(t1, t2) => + match (eval(t1), eval(t2)) { + (Abs(_, t1), t2) => eval(subst(t1, t2)) + (t1, t2) => App(t1, t2) + } + Abs(_) => self + // Eval should not encounter any free variables + _ => panic() + } +} + +test { + // (\x.x x) (\y.y) + let exp : Term = App(Abs("x", App(Var("x"), Var("x"))), Abs("x", Var("x"))) + let exp = exp.bruijn() + match exp { + Err(name) => fail!("err on \{name}\n") + Ok(t) => { + inspect!( + t, + content= + #|(\x.x x) (\x.x) + , + ) + let t = eval(t) + inspect!( + t, + content= + #|(\x.x) + , + ) + } + } +} diff --git a/next/tutorial/example/lambda/index.md b/next/tutorial/example/lambda/index.md index f68f9923..e9d0fddd 100644 --- a/next/tutorial/example/lambda/index.md +++ b/next/tutorial/example/lambda/index.md @@ -16,17 +16,17 @@ If we replace `x x` with `x(x)`, it might be more in line with the function call The combination of the above two expressions and the variables introduced when defining Lambdas are collectively referred to as the Lambda term. In MoonBit, we use an enum type to represent it: -```rust -enum Term { - Var(String) // Variable - Abs(String, Term) // Define lambda, variables represented by strings - App(Term, Term) // Call lambda -} +```{literalinclude} /sources/lambda-expression/src/top.mbt +:language: moonbit +:start-at: enum Term +:end-at: } ``` -Concepts encountered in daily programming such as boolean values, if expressions, natural number arithmetic, and even recursion can all be implemented using Lambda expressions. However, this is not the focus of this article. Interested readers can refer to: +Concepts encountered in daily programming such as boolean values, if expressions, natural number arithmetic, and even recursion can all be implemented using Lambda expressions. However, this is not the focus of this article. -- Programming with Nothing:[https://tomstu.art/programming-with-nothing](https://tomstu.art/programming-with-nothing) +```{seealso} +Interested readers can refer to: [Programming with Nothing](https://tomstu.art/programming-with-nothing) +``` To implement an interpreter for untyped Lambda calculus, the basic things we need to understand are just two rules: Alpha conversion and Beta reduction. @@ -34,13 +34,13 @@ To implement an interpreter for untyped Lambda calculus, the basic things we nee **Beta reduction** focuses on handling Lambda calls. Let's take an example: -```racket +``` (λx.(λy.x)) (λs.(λz.z)) ``` In untyped Lambda calculus, all that needs to be done after calling a Lambda is to substitute the parameter. In the example above, we need to replace the variable `x` with `(λs.(λz.z))`, resulting in: -```racket +``` (λy.(λs.(λz.z))) ``` @@ -50,13 +50,13 @@ If a variable in a Lambda term is not defined in its context, we call it a free During Beta reduction, if the Lambda term used for variable substitution contains free variables, it may lead to a behavior called "variable capture": -```racket +``` (λx.(λy.x)) (λz.y) ``` After substitution: -```racket +``` λy.λz.y ``` @@ -64,6 +64,8 @@ The free variable in `λz.y` is treated as a parameter of some Lambda, which is A common solution to the variable capture problem when writing interpreters is to traverse the expression before substitution to obtain a set of free variables. When encountering an inner Lambda during substitution, check if the variable name is in this set of free variables: + + ```moonbit // (λx.E) T => E.subst(x, T) fn subst(self : Term, var : String, term : Term) -> Term { @@ -89,7 +91,7 @@ Next, I'll introduce a less popular but somewhat convenient method: de Bruijn in De Bruijn index is a technique for representing variables in Lambda terms using integers. Specifically, it replaces specific variables with Lambdas between the variable and its original imported position. -```racket +``` λx.(λy.x (λz.z z)) λ.(λ.1 (λ.0 0)) @@ -101,59 +103,45 @@ In the example above, there is one Lambda `λy` between the variable `x` and its We define a new type `TermDBI` to represent Lambda terms using de Bruijn indices: -```moonbit -enum TermDBI { - Var(String, Int) - Abs(String, TermDBI) - App(TermDBI, TermDBI) -} +```{literalinclude} /sources/lambda-expression/src/top.mbt +:language: moonbit +:start-at: enum TermDBI +:end-at: } ``` -However, directly writing and reading Lambda terms in de Bruijn index form is painful, so we need to write a function `bruijn()` to convert `Term` to `TermDBI`. This is also why there is still a `String` in the definition of the `TermDBI` type, so that the original variable name can be used for its `to_string` method, making it easy to print and view the evaluation results with `println`. +However, directly writing and reading Lambda terms in de Bruijn index form is painful, so we need to write a function `bruijn()` to convert `Term` to `TermDBI`. This is also why there is still a `String` in the definition of the `TermDBI` type, so that the original variable name can be used for its `Show` implementation, making it easy to print and view the evaluation results with `println`. -```moonbit -fn to_string(self : TermDBI) -> String { - match self { - Var(name, _) => name - Abs(name, body) => "(\\\{name}.\{body})" - App(t1, t2) => "\{t1} \{t2}" - } -} +```{literalinclude} /sources/lambda-expression/src/top.mbt +:language: moonbit +:start-at: impl Show for TermDBI +:end-at: App(t1, t2) +:append: " }\n}" ``` To simplify implementation, if the input `Term` contains free variables, the `bruijn()` function will report an error directly. MoonBit provides a `Result[V, E]` type in the standard library, which has two constructors, `Ok(V)` and `Err(E)`, representing success and failure in computation, respectively. > Readers familiar with Rust should find this familiar. + ```moonbit fn bruijn(self : Term) -> Result[TermDBI, String] ``` We take a clumsy approach to save variable names and their associated nesting depth. First, we define the `Index` type: -```moonbit -struct Index { - name : String - depth : Int -} +```{literalinclude} /sources/lambda-expression/src/top.mbt +:language: moonbit +:start-at: struct Index +:end-at: } ``` Then we write a helper function to find the corresponding `depth` based on a specific `name` from `List[Index]`: -```moonbit -// Find the first depth corresponding to varname in the environment -fn find(map : @immut/list.T[Index], varname : String) -> Result[Int, String] { - match map { - Nil => Err(varname) // abort("variable '(varname)' not found") - Cons(i, rest) => { - if i.name == varname { - Ok(i.depth) - } else { - find(rest, varname) - } - } - } -} +```{literalinclude} /sources/lambda-expression/src/top.mbt +:language: moonbit +:dedent: +:start-at: // Find +:end-before: fn go ``` Now we can complete the `bruijn()` function. @@ -162,86 +150,34 @@ Now we can complete the `bruijn()` function. - `Abs` is a bit more complicated. First, add one to the `depth` of all `index` in the list (because the Lambda nesting depth has increased by one), and then add `{ name : varname, depth : 0 }` to the beginning of the list. - `App` succeeds when both sub-items can be converted; otherwise, it returns an `Err`. -```moonbit -fn go(m : @immut/list.T[Index], t : Term) -> Result[TermDBI, String] { - match t { - Var(name) => { - let idx = find(m, name) - match idx { - Err(name) => Err(name) - Ok(idx) => Ok(Var(name, idx)) - } - } - Abs(varname, body) => { - let m = m.map(fn (index){ - { name : index.name, depth : index.depth + 1 } - }).cons({ name : varname, depth : 0 }) - let res = go(m, body) - match res { - Err(name) => Err(name) - Ok(term) => Ok(Abs(varname, term)) - } - } - App(e1, e2) => { - match (go(m, e1), go(m, e2)) { - (Ok(e1), Ok(e2)) => Ok(App(e1, e2)) - (Err(name), _) => Err(name) - (_, Err(name)) => Err(name) - } - } - } -} -go(Nil, self) +```{literalinclude} /sources/lambda-expression/src/top.mbt +:language: moonbit +:start-at: fn go +:end-at: go(Nil, self) +:dedent: ``` ## Reduce on TermDBI Reduction mainly deals with App, i.e., calls: -```moonbit -fn eval(self : TermDBI) -> TermDBI { - match self { - App(t1, t2) => { - match (eval(t1), eval(t2)) { - (Abs(_, t1), t2) => eval(subst(t1, t2)) - (t1, t2) => App(t1, t2) - } - } - Abs(_) => self - otherwise => abort("eval(): \{otherwise} ") - // eval should not encounter free variables - } -} +```{literalinclude} /sources/lambda-expression/src/top.mbt +:language: moonbit +:start-at: fn eval +:end-before: test ``` First, attempt reduction on both sub-items, then see if `eval(t1)` results in a Lambda. If so, perform one step of variable substitution (via the subst function) and then continue simplifying. For Lambdas (`Abs`), simply return them as they are. The implementation of the subst function becomes much simpler when we don't need to consider free variables. We just need to keep track of the current depth recursively and compare it with the encountered variables. If they match, it's the variable to be replaced. -```moonbit -fn subst(t1 : TermDBI, t2 : TermDBI) -> TermDBI { - fn go(t1 : TermDBI, t2 : TermDBI, depth : Int) -> TermDBI { - match t1 { - Var(name, d) => { - if d == depth { - t2 - } else { - t1 - } - } - Abs(name, t) => { - Abs(name, go(t, t2, depth + 1)) - } - App(tl, tr) => { - App(go(tl, t2, depth), go(tr, t2, depth)) - } - } - } - go(t1, t2, 0) -} +```{literalinclude} /sources/lambda-expression/src/top.mbt +:language: moonbit +:start-at: fn subst +:end-before: fn eval ``` -The full code: [try.moonbitlang.com/#b52b528b](https://try.moonbitlang.com/#b52b528b) +The full code: [GitHub repository](https://github.com/moonbitlang/moonbit-docs/tree/main/next/sources/lambda-expression/src/top.mbt) ## Improvement