Calculating PI using streams, head & tail in DataWeave

Edit this site

Thanks to [head ~ tail] in DataWeave 2.0 we can easily create infinite sequence generators.

In this case we are implementing the Leibniz's series to calculate an approximation of PI.

/**
 * 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 )
}


---
// Then executing
pi(1E4)
// Outputs: 3.1415426585893202

s_j = \sum_{i} w_{ij}.y_{i}

where y_{i} is all the inputs (bias included)

After computing its state, the neuron passes it through its activation function (f_j), which normalizes the result (y_j) (normally between 0-1).

y_j = f_j(S_j)







G


cluster_0

process #1


cluster_1

process #2



a0

a0



a1

a1



a0->a1





a2

a2



a1->a2





b3

b3



a1->b3





a3

a3



a2->a3





a3->a0





end





end



a3->end





b0

b0



b1

b1



b0->b1





b2

b2



b1->b2





b2->a3





b2->b3





b3->end





start





start



start->a0





start->b0





Unformated typescript

function formatIfNeeded(code: string, language: string) {
  switch (language) {
    case "typescript":
    case "css":
    case "scss":
    case "json":
    case "yaml":
    case "json5":
    case "graphql":
    case "markdown":
    case "html":
      return prettier.format(code, { semi: false, parser: language })
    case "javascript":
      return prettier.format(code, { semi: false, parser: "babel" })
  }
  return code
}