Created
April 7, 2017 03:22
-
-
Save marcoslhc/2b15eb5e9469f549de55fda09081ca13 to your computer and use it in GitHub Desktop.
Functional Standard Deviation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Utilities | |
| const compose = | |
| (...fns) => (arg) => fns.reduceRight((composed, func) => func(composed), arg); | |
| const map = | |
| fn => list => list.map(fn); | |
| const filter = | |
| predicate => list => list.filter(predicate); | |
| const reduce = | |
| reducer => list => list.reduce(reducer, []); | |
| const mapReducer = | |
| fn => (accum, val) => accum.concat(fn(val)); | |
| const filterReducer = | |
| predicate => (accum, val) => (predicate(val) ? accum.concat(val) : accum); | |
| const tap = | |
| tag => x => (console.log(`${tag}: ${x}`), x); | |
| // Basic Arithmetics | |
| const sumAverage = | |
| list => list.reduce((sum, x) => x + sum, 0) / list.length; | |
| const exp = | |
| n => x => Math.pow(x, n); | |
| // Values | |
| const orders = [ | |
| 3, 5, 7, 8, 5, 25, 8, 4 | |
| ]; | |
| const average = sumAverage(orders); | |
| /******************************* | |
| * Stats | |
| *******************************/ | |
| const diff = | |
| average => order => order - average; | |
| const sqaredDiffs = | |
| compose(exp(2), diff(average)); | |
| // The variance is the sum of averages of sqared differences | |
| const variance = compose(sumAverage, map(sqaredDiffs)); | |
| // The standar deviation is the squared root of the variance | |
| const stdDev = | |
| compose(Math.sqrt, variance); | |
| const isNotable = | |
| filterReducer((base => (average, stdv) => elm => elm - average - stdv > base)(0)(average, stdDev(orders))); | |
| // Practical example | |
| // Get the values that stands out | |
| const notables = | |
| reduce(isNotable)(orders); | |
| console.log(notables); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment