From 431b6727aff534fefdf69608a70712ee93f81369 Mon Sep 17 00:00:00 2001 From: myfreess Date: Mon, 9 Dec 2024 10:48:33 +0800 Subject: [PATCH] fix example/diff --- next/sources/diff/.gitignore | 2 + next/sources/diff/LICENSE | 202 +++++++++++++++ next/sources/diff/README.md | 1 + next/sources/diff/moon.mod.json | 10 + next/sources/diff/src/part1/bparray.mbt | 44 ++++ next/sources/diff/src/part1/diff.mbt | 44 ++++ next/sources/diff/src/part1/line.mbt | 59 +++++ next/sources/diff/src/part1/moon.pkg.json | 1 + next/sources/diff/src/part2/bparray.mbt | 43 ++++ next/sources/diff/src/part2/diff.mbt | 111 +++++++++ next/sources/diff/src/part2/edit.mbt | 52 ++++ next/sources/diff/src/part2/line.mbt | 58 +++++ next/sources/diff/src/part2/moon.pkg.json | 1 + next/sources/diff/src/part3/bparray.mbt | 43 ++++ next/sources/diff/src/part3/diff.mbt | 234 ++++++++++++++++++ next/sources/diff/src/part3/edit.mbt | 49 ++++ next/sources/diff/src/part3/line.mbt | 58 +++++ next/sources/diff/src/part3/moon.pkg.json | 1 + .../tutorial/example/myers-diff/myers-diff.md | 115 ++------- .../example/myers-diff/myers-diff2.md | 150 ++--------- .../example/myers-diff/myers-diff3.md | 133 ++-------- 21 files changed, 1074 insertions(+), 337 deletions(-) create mode 100644 next/sources/diff/.gitignore create mode 100644 next/sources/diff/LICENSE create mode 100644 next/sources/diff/README.md create mode 100644 next/sources/diff/moon.mod.json create mode 100644 next/sources/diff/src/part1/bparray.mbt create mode 100644 next/sources/diff/src/part1/diff.mbt create mode 100644 next/sources/diff/src/part1/line.mbt create mode 100644 next/sources/diff/src/part1/moon.pkg.json create mode 100644 next/sources/diff/src/part2/bparray.mbt create mode 100644 next/sources/diff/src/part2/diff.mbt create mode 100644 next/sources/diff/src/part2/edit.mbt create mode 100644 next/sources/diff/src/part2/line.mbt create mode 100644 next/sources/diff/src/part2/moon.pkg.json create mode 100644 next/sources/diff/src/part3/bparray.mbt create mode 100644 next/sources/diff/src/part3/diff.mbt create mode 100644 next/sources/diff/src/part3/edit.mbt create mode 100644 next/sources/diff/src/part3/line.mbt create mode 100644 next/sources/diff/src/part3/moon.pkg.json diff --git a/next/sources/diff/.gitignore b/next/sources/diff/.gitignore new file mode 100644 index 00000000..b1283a74 --- /dev/null +++ b/next/sources/diff/.gitignore @@ -0,0 +1,2 @@ +target/ +.mooncakes/ diff --git a/next/sources/diff/LICENSE b/next/sources/diff/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/next/sources/diff/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/diff/README.md b/next/sources/diff/README.md new file mode 100644 index 00000000..380aaac7 --- /dev/null +++ b/next/sources/diff/README.md @@ -0,0 +1 @@ +# moonbit-community/diff \ No newline at end of file diff --git a/next/sources/diff/moon.mod.json b/next/sources/diff/moon.mod.json new file mode 100644 index 00000000..4301aaaa --- /dev/null +++ b/next/sources/diff/moon.mod.json @@ -0,0 +1,10 @@ +{ + "name": "moonbit-community/diff", + "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/diff/src/part1/bparray.mbt b/next/sources/diff/src/part1/bparray.mbt new file mode 100644 index 00000000..9aab13ae --- /dev/null +++ b/next/sources/diff/src/part1/bparray.mbt @@ -0,0 +1,44 @@ +// start bparray definition +type BPArray[T] Array[T] // BiPolar Array + +fn BPArray::make[T](capacity : Int, default : T) -> BPArray[T] { + let arr = Array::make(capacity, default) + BPArray(arr) +} + +fn copy(self : BPArray[Int]) -> BPArray[Int] { + let BPArray(arr) = self + let newarr = Array::make(arr.length(), 0) + for i = 0; i < arr.length(); i = i + 1 { + newarr[i] = arr[i] + } else { + BPArray(newarr) + } +} + +fn op_get[T](self : BPArray[T], idx : Int) -> T { + let BPArray(arr) = self + if idx < 0 { + arr[arr.length() + idx] + } else { + arr[idx] + } +} + +fn op_set[T](self : BPArray[T], idx : Int, elem : T) -> Unit { + let BPArray(arr) = self + if idx < 0 { + arr[arr.length() + idx] = elem + } else { + arr[idx] = elem + } +} +// end bparray definition + +test "bparray" { + let foo = BPArray::make(10, "foo") + foo[9] = "bar" + foo[8] = "baz" + assert_eq!(foo[-1], "bar") + assert_eq!(foo[-2], "baz") +} \ No newline at end of file diff --git a/next/sources/diff/src/part1/diff.mbt b/next/sources/diff/src/part1/diff.mbt new file mode 100644 index 00000000..8cb3e0b3 --- /dev/null +++ b/next/sources/diff/src/part1/diff.mbt @@ -0,0 +1,44 @@ +// start shortest_edit definition +fn shortest_edit(old~ : Array[Line], new~ : Array[Line]) -> Int { + let n = old.length() + let m = new.length() + let max = n + m + let v = BPArray::make(2 * max + 1, 0) + // v[1] = 0 + for d = 0; d < max + 1; d = d + 1 { + for k = -d; k < d + 1; k = k + 2 { + let mut x = 0 + let mut y = 0 + // if d == 0 { + // x = 0 + // } + if k == -d || (k != d && v[k - 1] < v[k + 1]) { + x = v[k + 1] + } else { + x = v[k - 1] + 1 + } + y = x - k + while x < n && y < m && old[x].text == new[y].text { + // Skip all matching lines + x = x + 1 + y = y + 1 + } + v[k] = x + if x >= n && y >= m { + return d + } + } + } else { + abort("impossible") + } +} +// end shortest_edit definition + +test "shortest_edit" { + let old = lines("aaa\naaa\naaa") + let new = lines("bbb\nbbb\nbbb") + inspect!(shortest_edit(old~, new~), content = "6") + let old = lines("A\nB\nC\nA\nB\nB\nA") + let new = lines("C\nB\nA\nB\nA\nC") + inspect!(shortest_edit(old~, new~), content = "5") +} \ No newline at end of file diff --git a/next/sources/diff/src/part1/line.mbt b/next/sources/diff/src/part1/line.mbt new file mode 100644 index 00000000..5a3f67df --- /dev/null +++ b/next/sources/diff/src/part1/line.mbt @@ -0,0 +1,59 @@ +// start line definition +struct Line { + number : Int // Line number + text : String // Does not include newline +} derive(Show) + +fn Line::new(number : Int, text : String) -> Line { + Line::{ number, text } +} +// end line definition + +// start lines definition +fn lines(str : String) -> Array[Line] { + let mut line_number = 0 + let buf = @buffer.new(size_hint=50) + let lines = [] + for i = 0; i < str.length(); i = i + 1 { + let ch = str[i] + if ch == '\n' { + let text = buf.to_unchecked_string() + buf.reset() + line_number = line_number + 1 + lines.push(Line::new(line_number, text)) + } else { + buf.write_char(ch) + } + } else { + // The text may not end with a newline + let text = buf.to_unchecked_string() + if text != "" { + line_number = line_number + 1 + lines.push(Line::new(line_number, text)) + } + lines + } +} +// end lines definition + +test "lines" { + inspect!(lines(""), content="[]") + inspect!( + lines("\n"), + content= + #|[{number: 1, text: ""}] + , + ) + inspect!( + lines("aaa"), + content= + #|[{number: 1, text: "aaa"}] + , + ) + inspect!( + lines("aaa\nbbb"), + content= + #|[{number: 1, text: "aaa"}, {number: 2, text: "bbb"}] + , + ) +} diff --git a/next/sources/diff/src/part1/moon.pkg.json b/next/sources/diff/src/part1/moon.pkg.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/next/sources/diff/src/part1/moon.pkg.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/next/sources/diff/src/part2/bparray.mbt b/next/sources/diff/src/part2/bparray.mbt new file mode 100644 index 00000000..f5d7deb2 --- /dev/null +++ b/next/sources/diff/src/part2/bparray.mbt @@ -0,0 +1,43 @@ +type BPArray[T] Array[T] // BiPolar Array + + +fn BPArray::make[T](capacity : Int, default : T) -> BPArray[T] { + let arr = Array::make(capacity, default) + BPArray(arr) +} + +fn copy(self : BPArray[Int]) -> BPArray[Int] { + let BPArray(arr) = self + let newarr = Array::make(arr.length(), 0) + for i = 0; i < arr.length(); i = i + 1 { + newarr[i] = arr[i] + } else { + BPArray(newarr) + } +} + +fn op_get[T](self : BPArray[T], idx : Int) -> T { + let BPArray(arr) = self + if idx < 0 { + arr[arr.length() + idx] + } else { + arr[idx] + } +} + +fn op_set[T](self : BPArray[T], idx : Int, elem : T) -> Unit { + let BPArray(arr) = self + if idx < 0 { + arr[arr.length() + idx] = elem + } else { + arr[idx] = elem + } +} + +test "bparray" { + let foo = BPArray::make(10, "foo") + foo[9] = "bar" + foo[8] = "baz" + assert_eq!(foo[-1], "bar") + assert_eq!(foo[-2], "baz") +} \ No newline at end of file diff --git a/next/sources/diff/src/part2/diff.mbt b/next/sources/diff/src/part2/diff.mbt new file mode 100644 index 00000000..e7ddf03f --- /dev/null +++ b/next/sources/diff/src/part2/diff.mbt @@ -0,0 +1,111 @@ + +// start shortest_edit definition +fn shortest_edit( + old~ : Array[Line], + new~ : Array[Line] +) -> Array[(BPArray[Int], Int)] { + let n = old.length() + let m = new.length() + let max = n + m + let v = BPArray::make(2 * max + 1, 0) + let trace = [] + fn push(v : BPArray[Int], d : Int) -> Unit { + trace.push((v, d)) + } + // v[1] = 0 + for d = 0; d < max + 1; d = d + 1 { + push(v.copy(), d) + for k = -d; k < d + 1; k = k + 2 { + let mut x = 0 + let mut y = 0 + // if d == 0 { + // x = 0 + // } + if k == -d || (k != d && v[k - 1] < v[k + 1]) { + x = v[k + 1] + } else { + x = v[k - 1] + 1 + } + y = x - k + while x < n && y < m && old[x].text == new[y].text { + x = x + 1 + y = y + 1 + } + v[k] = x + if x >= n && y >= m { + return trace + } + } + } else { + abort("impossible") + } +} +// end shortest_edit definition + + +// start backtrack_fst definition +fn backtrack( + new~ : Array[Line], + old~ : Array[Line], + trace : Array[(BPArray[Int], Int)] +) -> Array[Edit] { + let mut x = old.length() + let mut y = new.length() + let edits = Array::new(capacity=trace.length()) + // end backtrack_fst definition + // start backtrack_snd definition + for i = trace.length() - 1; i >= 0; i = i - 1 { + let (v, d) = trace[i] + let k = x - y + let prev_k = if k == -d || (k != d && v[k - 1] < v[k + 1]) { + k + 1 + } else { + k - 1 + } + let prev_x = v[prev_k] + let prev_y = prev_x - prev_k + while x > prev_x && y > prev_y { + x = x - 1 + y = y - 1 + edits.push(Equal(old=old[x], new=new[y])) + } + if d > 0 { + if x == prev_x { + edits.push(Insert(new=new[prev_y])) + } else if y == prev_y { + edits.push(Delete(old=old[prev_x])) + } + x = prev_x + y = prev_y + } + } + // end backtrack_snd definition + return edits +} + +// start diff definition +fn diff(old~ : Array[Line], new~ : Array[Line]) -> Array[Edit] { + let trace = shortest_edit(old~, new~) + backtrack(old~, new~, trace) +} +// end diff definition + +test "myers diff" { + let old = lines("A\nB\nC\nA\nB\nB\nA") + let new = lines("C\nB\nA\nB\nA\nC") + inspect!( + pprint_diff(diff(old~, new~)), + content= + #|- 1 A + #|- 2 B + #| 3 1 C + #|+ 2 B + #| 4 3 A + #| 5 4 B + #|- 6 B + #| 7 5 A + #|+ 6 C + #| + , + ) +} diff --git a/next/sources/diff/src/part2/edit.mbt b/next/sources/diff/src/part2/edit.mbt new file mode 100644 index 00000000..2757566d --- /dev/null +++ b/next/sources/diff/src/part2/edit.mbt @@ -0,0 +1,52 @@ +// start edit definition +enum Edit { + Insert(new~ : Line) + Delete(old~ : Line) + Equal(old~ : Line, new~ : Line) // old, new +} derive(Show) +// end edit definition + + +// start pprint definition +let line_width = 4 + +fn pad_right(s : String, width : Int) -> String { + String::make(width - s.length(), ' ') + s +} + +fn pprint_edit(edit : Edit) -> String { + match edit { + Insert(_) as edit => { + let tag = "+" + let old_line = pad_right("", line_width) + let new_line = pad_right(edit.new.number.to_string(), line_width) + let text = edit.new.text + "\{tag} \{old_line} \{new_line} \{text}" + } + Delete(_) as edit => { + let tag = "-" + let old_line = pad_right(edit.old.number.to_string(), line_width) + let new_line = pad_right("", line_width) + let text = edit.old.text + "\{tag} \{old_line} \{new_line} \{text}" + } + Equal(_) as edit => { + let tag = " " + let old_line = pad_right(edit.old.number.to_string(), line_width) + let new_line = pad_right(edit.new.number.to_string(), line_width) + let text = edit.old.text + "\{tag} \{old_line} \{new_line} \{text}" + } + } +} + +fn pprint_diff(diff : Array[Edit]) -> String { + let buf = @buffer.new(size_hint = 100) + for i = diff.length(); i > 0; i = i - 1 { + buf.write_string(pprint_edit(diff[i - 1])) + buf.write_char('\n') + } else { + buf.to_unchecked_string() + } +} +// end pprint definition \ No newline at end of file diff --git a/next/sources/diff/src/part2/line.mbt b/next/sources/diff/src/part2/line.mbt new file mode 100644 index 00000000..abd4dac5 --- /dev/null +++ b/next/sources/diff/src/part2/line.mbt @@ -0,0 +1,58 @@ +///| +struct Line { + number : Int // Line number + text : String // Does not include newline +} derive(Show) + +///| +fn Line::new(number : Int, text : String) -> Line { + Line::{ number, text } +} + +///| +fn lines(str : String) -> Array[Line] { + let mut line_number = 0 + let buf = @buffer.new(size_hint=50) + let lines = [] + for i = 0; i < str.length(); i = i + 1 { + let ch = str[i] + if ch == '\n' { + let text = buf.to_unchecked_string() + buf.reset() + line_number = line_number + 1 + lines.push(Line::new(line_number, text)) + } else { + buf.write_char(ch) + } + } else { + // The text may not end with a newline + let text = buf.to_unchecked_string() + if text != "" { + line_number = line_number + 1 + lines.push(Line::new(line_number, text)) + } + lines + } +} + +test "lines" { + inspect!(lines(""), content="[]") + inspect!( + lines("\n"), + content= + #|[{number: 1, text: ""}] + , + ) + inspect!( + lines("aaa"), + content= + #|[{number: 1, text: "aaa"}] + , + ) + inspect!( + lines("aaa\nbbb"), + content= + #|[{number: 1, text: "aaa"}, {number: 2, text: "bbb"}] + , + ) +} diff --git a/next/sources/diff/src/part2/moon.pkg.json b/next/sources/diff/src/part2/moon.pkg.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/next/sources/diff/src/part2/moon.pkg.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/next/sources/diff/src/part3/bparray.mbt b/next/sources/diff/src/part3/bparray.mbt new file mode 100644 index 00000000..f5d7deb2 --- /dev/null +++ b/next/sources/diff/src/part3/bparray.mbt @@ -0,0 +1,43 @@ +type BPArray[T] Array[T] // BiPolar Array + + +fn BPArray::make[T](capacity : Int, default : T) -> BPArray[T] { + let arr = Array::make(capacity, default) + BPArray(arr) +} + +fn copy(self : BPArray[Int]) -> BPArray[Int] { + let BPArray(arr) = self + let newarr = Array::make(arr.length(), 0) + for i = 0; i < arr.length(); i = i + 1 { + newarr[i] = arr[i] + } else { + BPArray(newarr) + } +} + +fn op_get[T](self : BPArray[T], idx : Int) -> T { + let BPArray(arr) = self + if idx < 0 { + arr[arr.length() + idx] + } else { + arr[idx] + } +} + +fn op_set[T](self : BPArray[T], idx : Int, elem : T) -> Unit { + let BPArray(arr) = self + if idx < 0 { + arr[arr.length() + idx] = elem + } else { + arr[idx] = elem + } +} + +test "bparray" { + let foo = BPArray::make(10, "foo") + foo[9] = "bar" + foo[8] = "baz" + assert_eq!(foo[-1], "bar") + assert_eq!(foo[-2], "baz") +} \ No newline at end of file diff --git a/next/sources/diff/src/part3/diff.mbt b/next/sources/diff/src/part3/diff.mbt new file mode 100644 index 00000000..ae1714ce --- /dev/null +++ b/next/sources/diff/src/part3/diff.mbt @@ -0,0 +1,234 @@ +// start box definition +struct Box { + left : Int + right : Int + top : Int + bottom : Int +} derive(Show) + +struct Snake { + start : (Int, Int) + end : (Int, Int) +} derive(Show) + +fn width(self : Box) -> Int { + self.right - self.left +} + +fn height(self : Box) -> Int { + self.bottom - self.top +} + +fn size(self : Box) -> Int { + self.width() + self.height() +} + +fn delta(self : Box) -> Int { + self.width() - self.height() +} +// end box definition +fn is_odd(n : Int) -> Bool { + (n & 1) == 1 +} + +fn is_even(n : Int) -> Bool { + (n & 1) == 0 +} + +// start search definition +fn forward( + self : Box, + forward~ : BPArray[Int], + backward~ : BPArray[Int], + depth : Int, + old~ : Array[Line], + new~ : Array[Line] +) -> Snake? { + for k = depth; k >= -depth; k = k - 2 { + let c = k - self.delta() + let mut x = 0 + let mut px = 0 + if k == -depth || (k != depth && forward[k - 1] < forward[k + 1]) { + x = forward[k + 1] + px = x + } else { + px = forward[k - 1] + x = px + 1 + } + let mut y = self.top + (x - self.left) - k + let py = if depth == 0 || x != px { y } else { y - 1 } + while x < self.right && y < self.bottom && old[x].text == new[y].text { + x = x + 1 + y = y + 1 + } + forward[k] = x + if is_odd(self.delta()) && + (c >= -(depth - 1) && c <= depth - 1) && + y >= backward[c] { + return Some(Snake::{ start: (px, py), end: (x, y) }) + } + } + return None +} + + +fn backward( + self : Box, + forward~ : BPArray[Int], + backward~ : BPArray[Int], + depth : Int, + old~ : Array[Line], + new~ : Array[Line] +) -> Snake? { + for c = depth; c >= -depth; c = c - 2 { + let k = c + self.delta() + let mut y = 0 + let mut py = 0 + if c == -depth || (c != depth && backward[c - 1] > backward[c + 1]) { + y = backward[c + 1] + py = y + } else { + py = backward[c - 1] + y = py - 1 + } + let mut x = self.left + (y - self.top) + k + let px = if depth == 0 || y != py { x } else { x + 1 } + while x > self.left && y > self.top && old[x - 1].text == new[y - 1].text { + x = x - 1 + y = y - 1 + } + backward[c] = y + if is_even(self.delta()) && (k >= -depth && k <= depth) && x <= forward[k] { + return Some(Snake::{ start: (x, y), end: (px, py) }) + } + } + return None +} +// end search definition + +// start midpoint definition +fn midpoint(self : Box, old~ : Array[Line], new~ : Array[Line]) -> Snake? { + if self.size() == 0 { + return None + } + let max = { + let half = self.size() / 2 + if is_odd(self.size()) { + half + 1 + } else { + half + } + } + let vf = BPArray::make(2 * max + 1, 0) + vf[1] = self.left + let vb = BPArray::make(2 * max + 1, 0) + vb[1] = self.bottom + for d = 0; d < max + 1; d = d + 1 { + match self.forward(forward = vf, backward = vb, d, old~, new~) { + None => + match self.backward(forward = vf, backward = vb, d, old~, new~) { + None => continue + res => return res + } + res => return res + } + } else { + None + } +} +// end midpoint definition + +// start findpath definition +fn find_path( + box : Box, + old~ : Array[Line], + new~ : Array[Line] +) -> Iter[(Int, Int)]? { + guard let Some(snake) = midpoint(box, old~, new~) else { None => None } + let start = snake.start + let end = snake.end + let headbox = Box::{ + left: box.left, + top: box.top, + right: start.0, + bottom: start.1, + } + let tailbox = Box::{ + left: end.0, + top: end.1, + right: box.right, + bottom: box.bottom, + } + let head = find_path(headbox, old~, new~).or(Iter::singleton(start)) + let tail = find_path(tailbox, old~, new~).or(Iter::singleton(end)) + Some(head.concat(tail)) +} +// end findpath definition + + +fn linear_diff(old~ : Array[Line], new~ : Array[Line]) -> Array[Edit]? { + let initial_box = Box::{ + left: 0, + top: 0, + right: old.length(), + bottom: new.length(), + } + guard let Some(path) = find_path(initial_box, old~, new~) else { + None => None + } + // path length >= 2 + let xy = path.take(1).collect()[0] // (0, 0) + let mut x1 = xy.0 + let mut y1 = xy.1 + let edits = Array::new(capacity=old.length() + new.length()) + path + .drop(1) + .each( + fn(xy) { + let x2 = xy.0 + let y2 = xy.1 + while x1 < x2 && y1 < y2 && old[x1].text == new[y1].text { + edits.push(Equal(old=old[x1], new=new[y1])) + x1 = x1 + 1 + y1 = y1 + 1 + } + if x2 - x1 < y2 - y1 { + edits.push(Insert(new=new[y1])) + y1 += 1 + } + if x2 - x1 > y2 - y1 { + edits.push(Delete(old=old[x1])) + x1 += 1 + } + while x1 < x2 && y1 < y2 && old[x1].text == new[y1].text { + edits.push(Equal(old=old[x1], new=new[y1])) + x1 = x1 + 1 + y1 = y1 + 1 + } + x1 = x2 + y1 = y2 + }, + ) + return Some(edits) +} + +test "myers diff" { + let old = lines("A\nB\nC\nA\nB\nB\nA") + let new = lines("C\nB\nA\nB\nA\nC") + let r = linear_diff(old~, new~).unwrap() + inspect!( + pprint_diff(r), + content= + #|- 1 A + #|- 2 B + #| 3 1 C + #|- 4 A + #| 5 2 B + #|+ 3 A + #| 6 4 B + #| 7 5 A + #|+ 6 C + #| + , + ) +} diff --git a/next/sources/diff/src/part3/edit.mbt b/next/sources/diff/src/part3/edit.mbt new file mode 100644 index 00000000..dd28993c --- /dev/null +++ b/next/sources/diff/src/part3/edit.mbt @@ -0,0 +1,49 @@ +enum Edit { + Insert(new~ : Line) + Delete(old~ : Line) + Equal(old~ : Line, new~ : Line) // old, new +} derive(Show) + +// start pprint definition +let line_width = 4 + +fn pad_right(s : String, width : Int) -> String { + String::make(width - s.length(), ' ') + s +} + +fn pprint_edit(edit : Edit) -> String { + match edit { + Insert(_) as edit => { + let tag = "+" + let old_line = pad_right("", line_width) + let new_line = pad_right(edit.new.number.to_string(), line_width) + let text = edit.new.text + "\{tag} \{old_line} \{new_line} \{text}" + } + Delete(_) as edit => { + let tag = "-" + let old_line = pad_right(edit.old.number.to_string(), line_width) + let new_line = pad_right("", line_width) + let text = edit.old.text + "\{tag} \{old_line} \{new_line} \{text}" + } + Equal(_) as edit => { + let tag = " " + let old_line = pad_right(edit.old.number.to_string(), line_width) + let new_line = pad_right(edit.new.number.to_string(), line_width) + let text = edit.old.text + "\{tag} \{old_line} \{new_line} \{text}" + } + } +} + +fn pprint_diff(diff : Array[Edit]) -> String { + let buf = @buffer.new(size_hint = 100) + for i = 0; i < diff.length(); i = i + 1 { + buf.write_string(pprint_edit(diff[i])) + buf.write_char('\n') + } else { + buf.to_unchecked_string() + } +} +// end pprint definition \ No newline at end of file diff --git a/next/sources/diff/src/part3/line.mbt b/next/sources/diff/src/part3/line.mbt new file mode 100644 index 00000000..abd4dac5 --- /dev/null +++ b/next/sources/diff/src/part3/line.mbt @@ -0,0 +1,58 @@ +///| +struct Line { + number : Int // Line number + text : String // Does not include newline +} derive(Show) + +///| +fn Line::new(number : Int, text : String) -> Line { + Line::{ number, text } +} + +///| +fn lines(str : String) -> Array[Line] { + let mut line_number = 0 + let buf = @buffer.new(size_hint=50) + let lines = [] + for i = 0; i < str.length(); i = i + 1 { + let ch = str[i] + if ch == '\n' { + let text = buf.to_unchecked_string() + buf.reset() + line_number = line_number + 1 + lines.push(Line::new(line_number, text)) + } else { + buf.write_char(ch) + } + } else { + // The text may not end with a newline + let text = buf.to_unchecked_string() + if text != "" { + line_number = line_number + 1 + lines.push(Line::new(line_number, text)) + } + lines + } +} + +test "lines" { + inspect!(lines(""), content="[]") + inspect!( + lines("\n"), + content= + #|[{number: 1, text: ""}] + , + ) + inspect!( + lines("aaa"), + content= + #|[{number: 1, text: "aaa"}] + , + ) + inspect!( + lines("aaa\nbbb"), + content= + #|[{number: 1, text: "aaa"}, {number: 2, text: "bbb"}] + , + ) +} diff --git a/next/sources/diff/src/part3/moon.pkg.json b/next/sources/diff/src/part3/moon.pkg.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/next/sources/diff/src/part3/moon.pkg.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/next/tutorial/example/myers-diff/myers-diff.md b/next/tutorial/example/myers-diff/myers-diff.md index 6204fc97..23f354c5 100644 --- a/next/tutorial/example/myers-diff/myers-diff.md +++ b/next/tutorial/example/myers-diff/myers-diff.md @@ -207,80 +207,34 @@ You can see that in each round of searching, `k` is strictly within the range `[ Let's first define the `Line` struct, which represents a line in the text. -```rust -struct Line { - number : Int // Line number - text : String // Does not include newline -} derive(Debug, Show) - -fn Line::new(number : Int, text : String) -> Line { - Line::{ number : number, text : text } -} +```{literalinclude} /sources/diff/src/part1/line.mbt +:language: moonbit +:start-after: start line definition +:end-before: end line definition ``` Then, define a helper function that splits a string into `Array[Line]` based on newline characters. Note that line numbers start from 1. -```rust -fn lines(str : String) -> Array[Line] { - let mut line_number = 0 - let buf = Buffer::make(50) - let vec = [] - for i = 0; i < str.length(); i = i + 1 { - let ch = str[i] - buf.write_char(ch) - if ch == '\n' { - let text = buf.to_string() - buf.reset() - line_number = line_number + 1 - vec.push(Line::new(line_number, text)) - } - } else { - // The text may not end with a newline - let text = buf.to_string() - if text != "" { - line_number = line_number + 1 - vec.push(Line::new(line_number, text)) - } - vec - } -} +```{literalinclude} /sources/diff/src/part1/line.mbt +:language: moonbit +:start-after: start lines definition +:end-before: end lines definition ``` Next, we need to wrap the array so that it supports negative indexing because we will use the value of `k` as an index. -```rust -type BPArray[T] Array[T] // BiPolar Array - -fn BPArray::make[T](capacity : Int, default : T) -> BPArray[T] { - let arr = Array::make(capacity, default) - BPArray(arr) -} - -fn op_get[T](self : BPArray[T], idx : Int) -> T { - let BPArray(arr) = self - if idx < 0 { - arr[arr.length() + idx] - } else { - arr[idx] - } -} - -fn op_set[T](self : BPArray[T], idx : Int, elem : T) -> Unit { - let BPArray(arr) = self - if idx < 0 { - arr[arr.length() + idx] = elem - } else { - arr[idx] = elem - } -} +```{literalinclude} /sources/diff/src/part1/bparray.mbt +:language: moonbit +:start-after: start bparray definition +:end-before: end bparray definition ``` Now we can start writing the search function. Before searching for the complete path, let's start with our first goal to find the length of the shortest path (equal to the search depth). Here is the basic framework: ```rust -fn shortst_edit(a : Array[Line], b : Array[Line]) -> Int { - let n = a.length() - let m = b.length() +fn shortst_edit(old~ : Array[Line], new~ : Array[Line]) -> Int { + let n = old.length() + let m = new.length() let max = n + m let v = BPArray::make(2 * max + 1, 0) for d = 0; d < max + 1; d = d + 1 { @@ -299,7 +253,7 @@ But even at this point, it is still difficult to figure out what to do next, so if d == 0 { // When d equals 0, k must also equal 0 x = 0 y = x - k - while x < n && y < m && a[x].text == b[y].text { + while x < n && y < m && old[x].text == new[y].text { // Skip all matching lines x = x + 1 y = y + 1 @@ -342,39 +296,10 @@ if k == -d || (k != d && v[k - 1] < v[k + 1]) { Combining all the steps above, we get the following code: -```rust -fn shortst_edit(a : Array[Line], b : Array[Line]) -> Int { - let n = a.length() - let m = b.length() - let max = n + m - let v = BPArray::make(2 * max + 1, 0) - // v[1] = 0 - for d = 0; d < max + 1; d = d + 1 { - for k = -d; k < d + 1; k = k + 2 { - let mut x = 0 - let mut y = 0 - // if d == 0 { - // x = 0 - // } - if k == -d || (k != d && v[k - 1] < v[k + 1]) { - x = v[k + 1] - } else { - x = v[k - 1] + 1 - } - y = x - k - while x < n && y < m && a[x].text == b[y].text { - x = x + 1 - y = y + 1 - } - v[k] = x - if x >= n && y >= m { - return d - } - } - } else { - abort("impossible") - } -} +```{literalinclude} /sources/diff/src/part1/diff.mbt +:language: moonbit +:start-after: start shortest_edit definition +:end-before: end shortest_edit definition ``` Since the initial value of the array is 0, we can omit the branch for `d == 0`. diff --git a/next/tutorial/example/myers-diff/myers-diff2.md b/next/tutorial/example/myers-diff/myers-diff2.md index 10fe761b..86b45850 100644 --- a/next/tutorial/example/myers-diff/myers-diff2.md +++ b/next/tutorial/example/myers-diff/myers-diff2.md @@ -6,70 +6,28 @@ This is the second post in the diff series. In the [previous one](https://www.mo The first step to obtaining the complete edit sequence is to save the entire editing process. This step is relatively simple; we just need to save the current search depth `d` and the graph node with depth `d` at the beginning of each search round. -```rust -fn shortest_edit(a : Array[Line], b : Array[Line]) -> Array[(BPArray[Int], Int)] { - let n = a.length() - let m = b.length() - let max = n + m - let v = BPArray::make(2 * max + 1, 0) - let trace = [] - fn push(v : BPArray[Int], d : Int) -> Unit { - trace.push((v, d)) - } - // v[1] = 0 - for d = 0; d < max + 1; d = d + 1 { - push(v.copy(), d) // Save search depth and node - for k = -d; k < d + 1; k = k + 2 { - let mut x = 0 - let mut y = 0 - // if d == 0 { - // x = 0 - // } - if k == -d || (k != d && v[k - 1] < v[k + 1]) { - x = v[k + 1] - } else { - x = v[k - 1] + 1 - } - y = x - k - while x < n && y < m && a[x].text == b[y].text { - x = x + 1 - y = y + 1 - } - - v[k] = x - if x >= n && y >= m { - return trace - } - } - } else { - abort("impossible") - } -} +```{literalinclude} /sources/diff/src/part2/diff.mbt +:language: moonbit +:start-after: start shortest_edit definition +:end-before: end shortest_edit definition ``` ## Backtracking the Edit Path After recording the entire search process, the next step is to walk back from the endpoint to find the path taken. But before we do that, let's first define the `Edit` type. -```rust -enum Edit { - Insert(~new : Line) - Delete(~old : Line) - Equal(~old : Line, ~new : Line) // old, new -} derive(Debug, Show) +```{literalinclude} /sources/diff/src/part2/edit.mbt +:language: moonbit +:start-after: start edit definition +:end-before: end edit definition ``` Next, let's perform the backtracking. -```rust -fn backtrack(a : Array[Line], b : Array[Line], trace : Array[(BPArray[Int], Int)]) -> Array[Edit] { - let mut x = a.length() - let mut y = b.length() - let edits = [] - fn push(edit : Edit) -> Unit { - edits.push(edit) - } - ...... +```{literalinclude} /sources/diff/src/part2/diff.mbt +:language: moonbit +:start-after: start backtrack_fst definition +:end-before: end backtrack_fst definition ``` The method of backtracking is essentially the same as forward search, just in reverse. @@ -86,87 +44,29 @@ The method of backtracking is essentially the same as forward search, just in re - Continue iterating. -```rust - for i = trace.length() - 1; i >= 0; i = i - 1 { - let (v, d) = trace[i] - let k = x - y - let prev_k = if k == -d || (k != d && v[k - 1] < v[k + 1]) { - k + 1 - } else { - k - 1 - } - let prev_x = v[prev_k] - let prev_y = prev_x - prev_k - while x > prev_x && y > prev_y { - x = x - 1 - y = y - 1 - push(Equal(old = a[x], new = b[y])) - } - if d > 0 { - if x == prev_x { - push(Insert(new = b[prev_y])) - } else if y == prev_y { - push(Delete(old = a[prev_x])) - } - x = prev_x - y = prev_y - } - } +```{literalinclude} /sources/diff/src/part2/diff.mbt +:language: moonbit +:dedent: +:start-after: start backtrack_snd definition +:end-before: end backtrack_snd definition ``` Combining the two functions, we get a complete `diff` implementation. -```rust -fn diff(a : Array[Line], b : Array[Line]) -> Array[Edit] { - let trace = shortest_edit(a, b) - backtrack(a, b, trace) -} +```{literalinclude} /sources/diff/src/part2/diff.mbt +:language: moonbit +:start-after: start diff definition +:end-before: end diff definition ``` ## Printing the Diff To print a neat diff, we need to left-align the text. Also, due to the order issue during backtracking, we need to print from back to front. -```rust -let line_width = 4 - -fn pad_right(s : String, width : Int) -> String { - String::make(width - s.length(), ' ') + s -} - -fn print_edit(edit : Edit) -> String { - match edit { - Insert(_) as edit => { - let tag = "+" - let old_line = pad_right("", line_width) - let new_line = pad_right(edit.new.number.to_string(), line_width) - let text = edit.new.text - "\{tag} \{old_line} \{new_line} \{text}" - } - Delete(_) as edit => { - let tag = "-" - let old_line = pad_right(edit.old.number.to_string(), line_width) - let new_line = pad_right("", line_width) - let text = edit.old.text - "\{tag} \{old_line} \{new_line} \{text}" - } - Equal(_) as edit => { - let tag = " " - let old_line = pad_right(edit.old.number.to_string(), line_width) - let new_line = pad_right(edit.new.number.to_string(), line_width) - let text = edit.old.text - "\{tag} \{old_line} \{new_line} \{text}" - } - } -} - -fn print_diff(diff : Array[Edit]) -> Unit { - for i = diff.length() - 1; i >= 0; i = i - 1 { - diff[i] - |> print_edit - |> println - } -} +```{literalinclude} /sources/diff/src/part2/edit.mbt +:language: moonbit +:start-after: start pprint definition +:end-before: end pprint definition ``` The result is as follows: diff --git a/next/tutorial/example/myers-diff/myers-diff3.md b/next/tutorial/example/myers-diff/myers-diff3.md index c18e039e..b16fd8f2 100644 --- a/next/tutorial/example/myers-diff/myers-diff3.md +++ b/next/tutorial/example/myers-diff/myers-diff3.md @@ -71,52 +71,18 @@ How do we determine if the searches overlap? Simply check if the position on a d We'll start by defining `Snake` and `Box` types, representing the middle snake and the sub-edit graphs (since they're square, we call them `Box`). -```rust -struct Box { - left : Int, - right : Int, - top : Int, - bottom : Int -} derive(Debug, Show) - -struct Snake { - start : (Int, Int), - end : (Int, Int) -} derive(Debug, Show) - -fn width(self : Box) -> Int { - self.right - self.left -} - -fn height(self : Box) -> Int { - self.bottom - self.top -} - -fn size(self : Box) -> Int { - self.width() + self.height() -} - -fn delta(self : Box) -> Int { - self.width() - self.height() -} +```{literalinclude} /sources/diff/src/part3/diff.mbt +:language: moonbit +:start-after: start box definition +:end-before: end box definition ``` To avoid getting bogged down in details too early, let's assume we already have a function `midpoint : (Box, Array[Line], Array[Line]) -> Snake?` to find the middle snake. Then, we can build the function `find_path` to search for the complete path. -```rust -fn find_path(box : Box, a : Array[Line], b : Array[Line]) -> Iter[(Int, Int)]? { - let snake = midpoint(box, a, b)?; - let start = snake.start; - let end = snake.end; - let headbox = Box { left: box.left, top: box.top, right: start.0, bottom: start.1 }; - let tailbox = Box { left: end.0, top: end.1, right: box.right, bottom: box.bottom }; - // println("snake = \{snake}") - // println("headbox = \{headbox}") - // println("tailbox = \{tailbox}") - let head = find_path(headbox, a, b).or(Iter::singleton(start)); - let tail = find_path(tailbox, a, b).or(Iter::singleton(end)); - Some(head.concat(tail)) -} +```{literalinclude} /sources/diff/src/part3/diff.mbt +:language: moonbit +:start-after: start findpath definition +:end-before: end findpath definition ``` The implementation of `find_path` is straightforward, but `midpoint` is a bit more complex: @@ -126,35 +92,10 @@ The implementation of `find_path` is straightforward, but `midpoint` is a bit mo - Store the results of the forward and backward searches in two arrays. - Alternate between forward and backward searches, returning `None` if no result is found. -```rust -fn midpoint(self : Box, a : Array[Line], b : Array[Line]) -> Snake? { - if self.size() == 0 { - return None; - } - let max = { - let half = self.size() / 2; - if is_odd(self.size()) { - half + 1 - } else { - half - } - }; - let vf = BPArray::make(2 * max + 1, 0); - vf[1] = self.left; - let vb = BPArray::make(2 * max + 1, 0); - vb[1] = self.bottom; - for d in 0..max + 1 { - match forward(self, vf, vb, d, a, b) { - None => - match backward(self, vf, vb, d, a, b) { - None => continue, - res => return res, - }, - res => return res, - } - } - None -} +```{literalinclude} /sources/diff/src/part3/diff.mbt +:language: moonbit +:start-after: start midpoint definition +:end-before: end midpoint definition ``` The forward and backward searches have some modifications compared to the original Myers algorithm, which need a bit of explanation: @@ -163,52 +104,10 @@ The forward and backward searches have some modifications compared to the origin - The search now works within a `Box` (not the global edit graph), so calculating `y` from `x` (or vice versa) requires conversion. - The backward search minimizes `y` as a heuristic strategy, but minimizing `x` would also work. -```rust -fn forward(self : Box, vf : BPArray, vb : BPArray, d : Int, a : Array[Line], b : Array[Line]) -> Snake? { - for k in (0..=d).rev() { - let c = k - self.delta(); - let (mut x, mut px) = if k == -d || (k != d && vf[k - 1] < vf[k - - + 1]) { - (vf[k + 1], vf[k + 1]) - } else { - (vf[k - 1] + 1, vf[k - 1]) - }; - let mut y = self.top + (x - self.left) - k; - let py = if d == 0 || x != px { y } else { y - 1 }; - while x < self.right && y < self.bottom && a[x].text == b[y].text { - x += 1; - y += 1; - } - vf[k] = x; - if is_odd(self.delta()) && (c >= -(d - 1) && c <= d - 1) && y >= vb[c] { - return Some(Snake { start: (px, py), end: (x, y) }); - } - } - None -} - -fn backward(self : Box, vf : BPArray, vb : BPArray, d : Int, a : Array[Line], b : Array[Line]) -> Snake? { - for c in (0..=d).rev() { - let k = c + self.delta(); - let (mut y, mut py) = if c == -d || (c != d && vb[c - 1] > vb[c + 1]) { - (vb[c + 1], vb[c + 1]) - } else { - (vb[c - 1] - 1, vb[c - 1]) - }; - let mut x = self.left + (y - self.top) + k; - let px = if d == 0 || y != py { x } else { x + 1 }; - while x > self.left && y > self.top && a[x - 1].text == b[y - 1].text { - x -= 1; - y -= 1; - } - vb[c] = y; - if is_even(self.delta()) && (k >= -d && k <= d) && x <= vf[k] { - return Some(Snake { start: (x, y), end: (px, py) }); - } - } - None -} +```{literalinclude} /sources/diff/src/part3/diff.mbt +:language: moonbit +:start-after: start search definition +:end-before: end search definition ``` ## Conclusion