From: Brendan Hansen Date: Tue, 20 Apr 2021 19:24:50 +0000 (-0500) Subject: added iter.fold and iter.take X-Git-Url: https://git.brendanfh.com/?a=commitdiff_plain;h=fdea2bf97788b74b28ffa0376ffe9137e476d21d;p=onyx.git added iter.fold and iter.take --- diff --git a/core/iter.onyx b/core/iter.onyx index 032fa2e8..601fa08c 100644 --- a/core/iter.onyx +++ b/core/iter.onyx @@ -73,8 +73,42 @@ map :: (it: Iterator($T), transform: (T) -> $R) -> Iterator(R) { }; } -fold :: (it: Iterator($T), initial_value: R = __zero_value(R), combine: (T, $R) -> R) -> R { - assert(false, "Not implemented yet"); +take :: (it: Iterator($T), count: u32) -> Iterator(T) { + TakeIterator :: struct (T: type_expr) { + iterator: Iterator(T); + remaining: u32; + } + + take_iterator := new(#type TakeIterator(T)); + take_iterator.iterator = it; + take_iterator.remaining = count; + + next :: ($T: type_expr, data: rawptr) -> (T, bool) { + ti := cast(^TakeIterator(T)) data; + if ti.remaining == 0 do return __zero_value(T), false; + + ti.remaining -= 1; + return ti.iterator.next(ti.iterator.data); + } + + close :: ($T: type_expr, data: rawptr) { + ti := cast(^TakeIterator(T)) data; + ti.iterator.close(ti.iterator.data); + cfree(data); + } + + return .{ + data = take_iterator, + next = #solidify next { T=T }, + close = #solidify close { T=T }, + }; +} + +fold :: (it: Iterator($T), initial_value: R, combine: (T, $R) -> R) -> R { + for value: it { + initial_value = combine(value, initial_value); + } + return initial_value; } diff --git a/tests/lazy_iterators.onyx b/tests/lazy_iterators.onyx index 58f48a25..0e75b701 100644 --- a/tests/lazy_iterators.onyx +++ b/tests/lazy_iterators.onyx @@ -37,20 +37,18 @@ count_iterator :: (lo: i32, hi: i32, step := 1) -> Iterator(i32) { main :: (args: [] cstr) { iterator := count_iterator(1, 10) - |> iter.map((x: i32) -> i32 do return x * 2;) - |> iter.filter((x: i32) -> bool do return x > 10;) - |> iter.map((x: i32) -> i32 do return x + 42;); + |> iter.map((x: i32) -> i32 { return x * 2; }) + |> iter.filter((x: i32) -> bool { return x > 10; }) + |> iter.map((x: i32) -> i32 { return x + 42; }); println("Starting the iteration..."); - for i: iterator { - println(i); - } + for i: iterator do println(i); arr := count_iterator(1, 10) - |> iter.map((x: i32) -> i32 do return x * 2;) - |> iter.filter((x: i32) -> bool do return x > 10;) - |> iter.map((x: i32) -> i32 do return x + 42;) - |> iter.to_array(); + |> iter.map((x: i32) -> i32 { return x * 2; }) + |> iter.filter((x: i32) -> bool { return x > 10; }) + |> iter.map((x: i32) -> i32 { return x + 42; }) + |> iter.to_array(); println(arr[2]); }