Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert simple average function in javascript to pointfree form using Ramda?

How do I convert the following simple average function to pointfree form (using Ramda)?

var _average = function(xs) {
  return R.reduce(R.add, 0, xs) / xs.length;
};

I've been this for a while now, but the R.divide function is throwing me off since the numerator and the denominator requires evaluation first

like image 889
Chad Avatar asked Dec 30 '25 21:12

Chad


2 Answers

Using R.converge:

//    average :: Array Number -> Number
const average = R.converge(R.divide, [R.sum, R.length]);

Using R.lift (which a more generally applicable function than R.converge):

//    average :: Array Number -> Number
const average = R.lift(R.divide)(R.sum, R.length);
like image 117
davidchambers Avatar answered Jan 02 '26 12:01

davidchambers


Here's one way to do it:

let xs = [5, 5];
let average = R.compose(R.apply(R.divide), R.juxt([R.sum, R.length]));
console.log(average(xs));
<script src="//cdn.jsdelivr.net/ramda/latest/ramda.min.js"></script>

Basically, R.juxt maps the array values into R.sum and R.length which gives you an array with the sum of the array and the length of the array. The result is applied to R.divide.

like image 43
MinusFour Avatar answered Jan 02 '26 14:01

MinusFour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!