DataWeave 2 - Generate Fibonacci sequence
In this post, we will see how to generate a Fibonacci sequence using DataWeave 2.
Fibonacci Sequence
Fibonacci number sequence is a series of numbers where each number is the sum of two preceding ones, starting from 0 and 1.
Generating Fibonacci sequence in DataWeave
We can generate Fibonacci sequence in DataWeave with a simple recursive function.
Script | Output (application/json) |
---|---|
%dw 2.0 output application/json indent=false fun fibonacci(limit:Number,series:Array<Number>) (1) = if (limit <= 0) series else fibonacci( limit - 1, series + (series[-1] + series[-2])) fun fibonacci(limit:Number) = fibonacci(limit, [0, 1]) (2) --- { limit10: fibonacci(10), (3) limit15: fibonacci(15, [13,21]) (4) } |
{ "limit10": [0,1,1,2,3,5,8,13,21,34,55,89], (5) "limit15": [13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657] (6) } |
1 | fibonacci function computing the sequence with a given number count limit. |
2 | Overloaded fibonacci function to start with default 0 and 1 as starting. |
3 | Get 10 fibonacci sequence numbers start from default 0 and 1 |
4 | Get 15 fibonacci sequence numbers after 13 and 21 sequential pair |
5 | Generated fibonacci for 10 numbers |
6 | Generated fibonacci for 15 numbers starting after 13 and 21 |
fibonacci
function uses a tail-recursion approach to avoid running into recursion stack limit. It keeps calling itself by decreasing the limit by 1 and adding a new number at the end of series. New number is calculated as sum of the preceding two numbers - Hence the Fibonacci sequence output.
fun fibonacci(limit:Number,series:Array<Number>)
= if (limit <= 0) series
else fibonacci( limit - 1, series + (series[-1] + series[-2]))
What is 103rd number in a Fibonacci sequence? Try running fibonacci(100) using above function. Hint: It is a 21-digit number :).
|
Conclusion
That’s all for this short post. It is not so difficult to write different functions in DataWeave 2. Hopefully, you learned something new here.
If you have any thoughts or feedback on this article, feel free to comment on this article or find me on Twitter or on manik.magar.me.
Stay updated!
On this blog, I post articles about different technologies like Java, MuleSoft, and much more.
You can get updates for new Posts in your email by subscribing to JavaStreets feed here -
Lives on Java Planet, Walks on Java Streets, Read/Writes in Java, JCP member, Jakarta EE enthusiast, MuleSoft Integration Architect, MuleSoft Community Ambassador, Open Source Contributor and Supporter, also writes at Unit Testers, A Family man!