From 838d67eb23dffdf8006e33ee1ec26b779f5c87bf Mon Sep 17 00:00:00 2001 From: Lampese Date: Sat, 9 Mar 2024 13:49:35 +0800 Subject: [PATCH 1/3] feat(array): add fold --- array/array.mbt | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/array/array.mbt b/array/array.mbt index 9ffd11168..2d86b465f 100644 --- a/array/array.mbt +++ b/array/array.mbt @@ -180,3 +180,14 @@ test "from_array" { let array = Array::[1, 2, 3, 4, 5] @assertion.assert_eq(array, [1, 2, 3, 4, 5])? } + +pub fn fold[T, U](self : Array[T], f : (T, U) -> U, init : U) -> U { + let mut result = init + self.iter(fn(elem : T) { result = f(elem, result) }) + result +} + +test "fold" { + let sum = [1, 2, 3, 4, 5].fold(fn(elem, sum : Int) { sum + elem }, 0) + @assertion.assert_eq(sum, 15)? +} From 1531b211649796f7b4b7fd25844efedbfd5f39a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=9C=E7=81=AF?= Date: Mon, 11 Mar 2024 23:09:01 +0800 Subject: [PATCH 2/3] more efficient --- array/array.mbt | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/array/array.mbt b/array/array.mbt index 2d86b465f..c1571587f 100644 --- a/array/array.mbt +++ b/array/array.mbt @@ -182,9 +182,11 @@ test "from_array" { } pub fn fold[T, U](self : Array[T], f : (T, U) -> U, init : U) -> U { - let mut result = init - self.iter(fn(elem : T) { result = f(elem, result) }) - result + for i = 0, acc = init ; i < self.length() ; { + continue i + 1, f(self[i], acc) + } else { + acc + } } test "fold" { From 031a0d63847b4dc1c4bb796cba292e68eab61fa6 Mon Sep 17 00:00:00 2001 From: Lampese Date: Tue, 12 Mar 2024 00:51:07 +0800 Subject: [PATCH 3/3] use function loop --- array/array.mbt | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/array/array.mbt b/array/array.mbt index c1571587f..ebb9209de 100644 --- a/array/array.mbt +++ b/array/array.mbt @@ -182,10 +182,14 @@ test "from_array" { } pub fn fold[T, U](self : Array[T], f : (T, U) -> U, init : U) -> U { - for i = 0, acc = init ; i < self.length() ; { - continue i + 1, f(self[i], acc) - } else { - acc + loop 0, init { + i, acc => + if i < self.length() { + continue i + 1, + f(self[i], acc) + } else { + acc + } } }