Fibonacci sequence #1469
Unanswered
andreavaccari
asked this question in
Q&A
Replies: 2 comments 6 replies
-
In strict language, manually tail recursion would do the trick: import { left, right } from 'fp-ts/Either';
import { tailRec } from 'fp-ts/ChainRec';
function fibEvenSum (n: number) {
const isEven = (num: bigint) => num % 2n === 0n;
const init = { a: 1n, b: 2n, i: 2, acc: 2n };
return tailRec(init, ({ a, b, i, acc }) => {
if (i >= n) {
return right(acc);
}
const c = a + b;
return left({
a: b,
b: c,
i: i + 1,
acc: isEven(c) ? acc + c : acc,
});
});
} note: although it's stack safe, do expect reasonable amount of CPU time against four million cycles. |
Beta Was this translation helpful? Give feedback.
4 replies
-
Since problem space is much smaller, another approach with import {
option as O,
function as F,
readonlyArray as A,
} from 'fp-ts';
const fibEvenSum2 = (n: number) => F.pipe(
A.unfold({ a: 1, b: 1 }, F.flow(
O.fromPredicate(({ b }) => b < n),
O.map(({ a, b }) => {
const c = a + b;
return [ c, { a: b, b: c } ];
}),
)),
A.filter(m => m % 2 === 0),
A.reduce(0, (a, b) => a + b),
); |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm learning
fp-ts
by solving Project Euler. Could someone show some ways to solve Problem 2?The Haskell wiki has various solutions, but I can't reimplement them with
fp-ts
.Thank you!
Beta Was this translation helpful? Give feedback.
All reactions