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.
- 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
3 Answers
Reset to default 9The 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
版权声明:本文标题:javascript - Pointfree version of a function using Ramda.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744592036a2614550.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论