简体   繁体   中英

Return array of applied functions with Ramda

I would like to call an Array of functions with a value and get an Array of the partially applied functions back.

My current code:

const my_array = pipe(flip(call), flip(map)([add, subtract]))(1)
// = [add(1), subtract(1)]

Is there a better way of doing this?

My goal (possibly unreasonable) would be to have a point-free alternative to the following function:

const bind_all = (funcs) => pipe(flip(call), flip(map)(funcs))
bind_all([add, subtract])(1)
// = [add(1), subtract(1)]

This seems to be similar to juxt , but returning an Array instead of a function.


Update: In response to the answers, I agree that my current code is far from readable, due to trying to force a point-free approach (with limited knowledge of existing patterns). This question is simply trying to explore the limits of point-free design that maintains readability.

The current answers seem to indicate that this is actually unreasonable.

I don't know why people insist on doing everything point-free when your code ends up looking like junk - flip this, flip that. what a brainf*ck.

pipe(flip(call), flip(map)([add, subtract]))(1)

If you have [add, subtract] and 1 and you wish to have [add(1), subtract(1)] just write the damned mapping function

map(f => f(1), [add, subtract])
// => [add(1), subtract(1)]

We can see how repeating this would give us fully applied functions

map(f => f(1), map(f => f(1), [add, subtract]))
// => [add(1)(1), subtract(1)(1)]
// => [2, 0]

If you're that fixated on writing everything point-free, write your own combinator

const $ = x => f => f (x)

R.map($(1), [R.add, R.subtract])
// => [add(1), subtract(1)]

R.map($(1), R.map($(1), [R.add, R.subtract]))
// => [add(1)(1), subtract(1)(1)]
// => [2,0]

Maybe I'm missing something, but juxt does seem to do what you need

juxt([add, flip(subtract)])(1)(7); //=> [8, 6]

Update: As pointed out in the comments, this did not capture the original requirements. I think the following approach does. It is similar to the one from @naomik , but creating a reusable function rather than simply running inline:

const callAll = curry((fns, arg) => map(fn => fn(arg), fns));

const partials = callAll([add, subtract], 10); //=> [add(10), subtract(10)]
callAll(partials, 3); //=> [10 + 3, 10 - 3] => [13, 7]

Obviously we could write this in a way that handles multiple parameters, if we desired. Using it once to create the partial functions, then again to apply the argument to them feels pretty elegant, too.

You can see this in action on the Ramda REPL .

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