简体   繁体   中英

Pointfree version of a function using Ramda.js

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.

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 = compose(flip(find)(items), propEq('id'))

Using ES6 syntax for brevity:

var {compose} = 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 = compose(flip(find)(items), propEq('id'))

console.log(search(2))

It is point-less though.

Demo: http://jsbin.com/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' }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM