5

I have a higher order function: let's say for simplicity

const divideLeftToRight = x => y => x/y;

I would like to have a function that performs the division but from 'right to left'. In other words, I need to have:

const divideRightToLeft = x => y => y/x;

I thought about doing:

const divideRightToLeft = R.curry((x,y) => divideLeftToRight(y)(x));

I am wondering if there is a more elegant way to do it

tcoder01
  • 159
  • 1
  • 2
  • 7
  • Don't forget you can use R.__ to not have to fudge around with getting the parameter order perfect if necessary. – Dan May 25 '22 at 23:01

2 Answers2

7

You are looking for the flip function:

const divideRightToLeft = R.flip(divideLeftToRight)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • flip does not work with my higher order function (unless tweeking maybe). http://ramdajs.com/repl/#?const%20divideLeftToRight%20%3D%20x%20%3D%3E%20y%20%3D%3E%20x%2Fy%3B%0A%0A%0Aconst%20divideRightToLeft%20%3D%20R.flip%28divideLeftToRight%29%0A%0AdivideRightToLeft%282%29%2833%29 if my function were: const divideLeftToRight = (x,y) => x/y; then the flipping of arguments would work – tcoder01 May 24 '17 at 10:34
  • Does `flip` work with functions curried by ramda itself (not through nested arrow functions)? – Bergi May 24 '17 at 10:37
  • @Bergi: not exactly. It flips the first two arguments of any (arity 2+) function. It would work fine with `(x, y) => x/y`. Or, alternately, one could use `flip` with `uncurryN`. But it doesn't know what to do with an arity-1 function. – Scott Sauyet May 24 '17 at 12:01
  • @ScottSauyet Can't it just assume that it is curried? `flip = f => f.length == 1 ? ((x) => (y, ...args) => f(y)(x, ...args)) : …` – Bergi May 24 '17 at 12:29
  • @Bergi: we probably could. It hasn't come up before that I recall, but it would make sense to do so. We'd need something a little more complex than that, because the result should probably look like the output of other Ramda functions with several distinct ways of calling it (`fn(y)(x)`, `fn(y, x)`, but that's a detail – Scott Sauyet May 24 '17 at 15:18
2

You could uncurry the function before flipping. (flip returns a curried function.)

E.g.

const divideRightToLeft = R.flip(R.uncurryN(2, divideLeftToRight))

Alternatively, you can define a custom flipCurried function:

// https://github.com/gcanti/fp-ts/blob/15f4f701ed2ba6b0d306ba7b8ca9bede223b8155/src/function.ts#L127
const flipCurried = <A, B, C>(fn: (a: A) => (b: B) => C) => (b: B) => (a: A) => fn(a)(b);

const divideRightToLeft = flipCurried(divideLeftToRight)
Oliver Joseph Ash
  • 3,138
  • 2
  • 27
  • 47