Forum Discussion
Viz
Jan 05, 2021Brass Contributor
Lambda Example: Generate Fibonacci series
In this post, I would like to explain how I have used Lambda to create a function to generate a Fibonacci series array. This example can also be used to understand how to create an array where th...
Patrick2788
Apr 24, 2023Silver Contributor
I realize this solution is not the most efficient but it was fun to create and it's a bit different (Inspired by Pascal's Triangle).
'DiagonalSum
=LAMBDA(a,v,VSTACK(
a,
IF(v < 3, 1, SUM(IFERROR(COMBIN(SEQUENCE(v - 1, , v - 1, -1), SEQUENCE(v - 1, , 0)), 0)))
))
'Fib
=LAMBDA(elements,REDUCE(0, SEQUENCE(elements), DiagonalSum))
- PeterBartholomew1Apr 24, 2023Silver Contributor
I think I am becoming conditioned! I only have to read the words Pascal's triangle and I find myself writing
=REDUCE(1, SEQUENCE(n), LAMBDA(triangle, k, LET( previous, TAKE(triangle, -1), left, HSTACK(previous, 0), right, HSTACK(0, previous), IFNA(VSTACK(triangle, left + right), "") ) ) )
- Patrick2788Apr 24, 2023Silver Contributor
Does that create a pyramid-like array?
I went with a left-justified version:
'Pascal =Lambda(n,DROP( REDUCE( "", SEQUENCE(, n), LAMBDA(a, v, VSTACK(a, EXPAND(COMBIN(v - 1, SEQUENCE(, v, 0)), , n, ""))) ), 1 ))
- PeterBartholomew1Apr 25, 2023Silver Contributor
No, like yours it is left stacked. Far more effort would be required for they layout than was needed for the calculation! The main difference is that mine is more primitive in that it uses the recurrence relation from row to row rather that the functional form of the result.
Since you mention it though, how about this?
= REDUCE(1, SEQUENCE(n), LAMBDA(triangle,k, LET( previous, TAKE(triangle, -1), left, HSTACK(previous, {0,0}), right, HSTACK({0,0}, previous), triangle, VSTACK(HSTACK(0,triangle), left + right), IFERROR(IF(triangle,triangle,""),"") ) ) )