admin管理员组文章数量:1323744
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
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
- 2 May be worth a read mail.haskell/pipermail/beginners/2011-June/007266.html – Xotic750 Commented Sep 16, 2016 at 16:13
- 1 Thanks for raising a great point regarding readability. And it is definitely good to remember that " If the point-free style isn't easy to write, it's probably also not easy to read." But as an exercise, how would you answer the question in case you had to. – Chad Commented Sep 16, 2016 at 16:22
- I don't honestly don't know and it looks like a headache. :) – Xotic750 Commented Sep 16, 2016 at 16:34
4 Answers
Reset to default 8Using 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);
Here's one way to do it:
let xs = [5, 5];
let average = R.pose(R.apply(R.divide), R.juxt([R.sum, R.length]));
console.log(average(xs));
<script src="//cdn.jsdelivr/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
.
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]));
Simpler one:
R.mean([1,3]) // returns 2
本文标签:
版权声明:本文标题:functional programming - How to convert simple average function in javascript to pointfree form using Ramda? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742118089a2421563.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论