Reputation: 2071
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
Upvotes: 3
Views: 1003
Reputation: 24806
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);
Upvotes: 8
Reputation: 1927
You can try the below one
var _sum = function(xs) {
return R.reduce(R.add, 0, xs);
};
var _average = function(xs) {
return R.divide(_sum(xs), xs.length);
};
console.log(_average([3,4,5,6]));
or simply
var _average = function(xs) {
return R.divide(R.reduce(R.add, 0, xs), xs.length);
};
console.log(_average([3,4,5,6]));
Upvotes: 0
Reputation: 14423
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
.
Upvotes: 5