Data update
This commit is contained in:
parent
aec8ed51b6
commit
29a5eea0d4
128 changed files with 1298 additions and 0 deletions
64
Task/Fibonacci-sequence/Onyx-(wasm)/fibonacci-sequence.onyx
Normal file
64
Task/Fibonacci-sequence/Onyx-(wasm)/fibonacci-sequence.onyx
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
use core.iter
|
||||
use core { printf }
|
||||
|
||||
// Procedural Simple For-Loop Style
|
||||
fib_for_loop :: (n: i32) -> i32 {
|
||||
a: i32 = 0;
|
||||
b: i32 = 1;
|
||||
for 0 .. n {
|
||||
tmp := a;
|
||||
a = b;
|
||||
b = tmp + b;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
FibState :: struct { a, b: u64 }
|
||||
|
||||
// Functional Folding Style
|
||||
fib_by_fold :: (n: i32) => {
|
||||
end_state :=
|
||||
iter.counter()
|
||||
|> iter.take(n)
|
||||
|> iter.fold(
|
||||
FibState.{ a = 0, b = 1 },
|
||||
(_, state) => FibState.{
|
||||
a = state.b,
|
||||
b = state.a + state.b
|
||||
}
|
||||
);
|
||||
return end_state.a;
|
||||
}
|
||||
|
||||
// Custom Iterator Style
|
||||
fib_iterator :: (n: i32) =>
|
||||
iter.generator(
|
||||
&.{ a = cast(u64) 0, b = cast(u64) 1, counter = n },
|
||||
(state: & $Ctx) -> (u64, bool) {
|
||||
if state.counter <= 0 {
|
||||
return 0, false;
|
||||
}
|
||||
tmp := state.a;
|
||||
state.a = state.b;
|
||||
state.b = state.b + tmp;
|
||||
state.counter -= 1;
|
||||
return tmp, true;
|
||||
}
|
||||
);
|
||||
|
||||
main :: () {
|
||||
printf("\nBy For Loop:\n");
|
||||
for i in 0 .. 21 {
|
||||
printf("{} ", fib_for_loop(i));
|
||||
}
|
||||
|
||||
printf("\n\nBy Iterator:\n");
|
||||
for i in 0 .. 21 {
|
||||
printf("{} ", fib_by_fold(i));
|
||||
}
|
||||
|
||||
printf("\n\nBy Fold:\n");
|
||||
for value, index in fib_iterator(21) {
|
||||
printf("{} ", value);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue