最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functional programming - How to convert simple average function in javascript to pointfree form using Ramda? - Stack Overflow

programmeradmin2浏览0评论

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

Share Improve this question asked Sep 16, 2016 at 15:46 ChadChad 2,0816 gold badges28 silver badges44 bronze badges 3
  • 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
Add a ment  | 

4 Answers 4

Reset to default 8

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);

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论