Skip to content

Instantly share code, notes, and snippets.

@menduz
Last active November 6, 2017 00:29
Show Gist options
  • Save menduz/dca670391a1147cd39cc3db3699de856 to your computer and use it in GitHub Desktop.
Save menduz/dca670391a1147cd39cc3db3699de856 to your computer and use it in GitHub Desktop.
Calculate PI using DataWeave
/**
* This function returns a stream. We first populate the stream with a head value,
* and a lazy tail.
* In this case, we tell the engine the tail is a function call.
* That function call will be not be executed UNTIL the value of that call is needed.
*/
fun leibnizTerm(n: Number = 0): Array<Number> =
[4 / (n + 1) - 4 / (n + 3) ~ leibnizTerm(n + 4)]
// ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
// head lazy tail
/**
* Now we have the sequence generator, the only thing left is select
* the values and aggregate them. We are going to pick a slice of the
* infinite sequence of leibnizTerm using a range selector.
*/
fun pi(terms: Number = 1E4): Number = do {
var seriesSubset = leibnizTerm()[0 to terms]
// ^^^^^^^^^^^ ^^^^^^^^^^^^
// series gen range selector
---
sum( seriesSubset )
}
---
pi(1E4)
// Outputs: 3.1415426585893202
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment