# ðŸ“˜ Computing standard deviation using Perl 6

For the given data, calculate the standard deviation value (sigma).

Standard deviation is a statistical term that shows how compact data distribution is. The formula is the following:

whereÂ N is the number of elements in the arrayÂ x;Â is the average value (see Task 56,Â Average on an array).

Letâ€™s use some test data from Wikipedia and take the straightforward approach using reduction operations and avoiding explicit loops:

`my @data = 727.7, 1086.5, 1091.0, 1361.3, 1490.5, 1956.1;my \$avg = ([+] @data) / @data.elems;my \$sigma = sqrt(    ([+] map * ** 2, map * - \$avg, @data) /    (@data.elems - 1));say \$sigma; # 420.962489619523`

Inside theÂ `sqrt` function, theÂ `[+]` reduction operator gets the array that is formed by the two nested runs ofÂ `map`. First, the constant shift has been removed by applyingÂ `* - \$avg` to each element. Second, a square of each item has been calculated:Â `* ** 2`.

In both cases, theÂ `WhateverCode` is used. It is usually more expressive but may lead to constructs likeÂ `* ** 2`, which look a bit cryptic.

The twoÂ `map`s can be merged into one:

`my \$sigma = sqrt(    ([+] map (* - \$avg) ** 2, @data)  / (@data.elems - 1));`

Now, letâ€™s explore the second approach that gets the same result usingÂ feed operators. In Perl 6, there are feed operators of both directions:Â `<==` andÂ  `==>`. Their shape indicates the direction of data flow, so here is another version of the program.

`my @data = 727.7, 1086.5, 1091.0, 1361.3, 1490.5, 1956.1;my \$avg = ([+] @data) / @data.elems;@data    ==> map * - \$avg    ==> map * ** 2    ==> reduce * + *    ==> my @Ïƒ;say sqrt(@Ïƒ[0] / (@data.elems - 1)); # 420.962489619523`

The data flow is clearly visible now. TheÂ `@data` array passes the two `map`s, and then, it is reduced using theÂ `+` operation. The call ofÂ reduce `* + *` is equivalent to using the reduction operator in the form ofÂ `[+]`.

Notice how theÂ `@Ïƒ` array is defined, not only the fact that a Unicode name is used but mostly the fact that theÂ `my` declaration is placed at the end of the feed chain. An array is used here becauseÂ theÂ feed operator does not return a scalar value, although we only need one element.

To make the code even closer to the original mathematical formula, you may choose a different name for the variable holding the average value (and remove theÂ elemscall):

`my \$xÌ„= ([+] @data) / @data;`