admin管理员组

文章数量:1394143

I am trying to make the following function pointfree. I am not sure how I can pass the arguement to the inner function though. I am using Ramda.js, but I think the concept is more general than that. Here is the code I have.

search = function(id) {
  return find(propEq('id', id), items)
}

Here, you will notice that the id parameter is passed to the inner function propEq. That's the part I am unsure of.

I am trying to make the following function pointfree. I am not sure how I can pass the arguement to the inner function though. I am using Ramda.js, but I think the concept is more general than that. Here is the code I have.

search = function(id) {
  return find(propEq('id', id), items)
}

Here, you will notice that the id parameter is passed to the inner function propEq. That's the part I am unsure of.

Share Improve this question asked Aug 5, 2015 at 4:55 Nachiket MehtaNachiket Mehta 3103 silver badges15 bronze badges 2
  • I'm not sure I understand what your problem is. Also, the code you posted is already point-free. – azium Commented Aug 5, 2015 at 5:00
  • 2 @azium, It is not point-free, id is the point. – elclanrs Commented Aug 5, 2015 at 5:02
Add a ment  | 

3 Answers 3

Reset to default 9

The question is more general than Ramda, but Ramda does have several functions to make things like this easier, especially useWith and converge.

This can be written points-free with useWith like this:

var search = useWith(find, propEq('id'), identity);
search(2, items); //=> {id:  2}

You can see it in action on the Ramda REPL.

With a bit of tinkering you can get a point-free version, but the auto-currying gave issues, so I had to duplicate some functionality by currying the functions manually. This is the one liner:

search = pose(flip(find)(items), propEq('id'))

Using ES6 syntax for brevity:

var {pose} = R

var find = f => xs => R.find(f, xs)
var propEq = p => x => R.propEq(p, x)
var flip = f => a => b => f(b)(a)

// Example:

var items = [{id: 1}, {id: 2}, {id: 3}]

// point-full
var search = function(id) {
  return find(propEq('id')(id))(items)
}

console.log(search(2))

// point-free
search = pose(flip(find)(items), propEq('id'))

console.log(search(2))

It is point-less though.

Demo: http://jsbin./batedi/edit?js,output

You just have to curry it first. Then you can give it the id first, and items will be the output of the function that precedes it.

Ex:

const search = R.curry((id, items) => R.find(R.propEq('id', id), items));

const testSearch = R.pipe(
  R.identity(() => [{id: '123'}, {id: 'asdf'}]),
  search('123')
);

testSearch(); // { id: '123' }

本文标签: javascriptPointfree version of a function using RamdajsStack Overflow