These are chat archives for ramda/ramda

2nd
Dec 2018
Greg Fagan
@gregfagan
Dec 02 2018 00:36
I don't understand why this middle statement doesn't work:
``````always(identity)(undefined)(1) // 1
ifElse(isNil, always(identity), add)(undefined)(1) // function () ...
ifElse(isNil, always(identity), add)(2)(1) // 3``````
I basically want something like `unless` except that if the predicate fails instead of calling `identity` on the argument it returns the identity function
Greg Fagan
@gregfagan
Dec 02 2018 00:43
maybe this is clearer:
``````const safeAdd = ifElse(isNil, always(identity), add)
safeAdd(undefined)(3) // should be 3, instead is a fn``````
Kurt Milam
@kurtmilam
Dec 02 2018 12:27
@gregfagan That has something to do with Ramda's smart currying, I believe. I was surprised to find that it also doesn't work as expected if you call `safeAdd` with `null`, first.
This 'dumb' curried `ifElse` replacement works:
``````const ifte = p => t => f => x => p(x) === true ? t(x) : f(x)
const safeAdd = ifte(isNil)(always(identity))(add)
safeAdd(undefined)(3) // -> 3
safeAdd(null)(3) // -> 3``````
I wonder whether that's a bug.
Kurt Milam
@kurtmilam
Dec 02 2018 12:56
Probably not a bug - `ifElse` is curried based on the longest function passed to it (`add`, in this case, with arity 2), so the function returned by `ifElse` isn't evaluated until it has been called with two arguments.
Wrapping `add` in `unary` also fixes it:
``````const safeAdd = ifElse(isNil, always(identity), unary(add))
safeAdd(undefined)(3) // -> 3``````
Kurt Milam
@kurtmilam
Dec 02 2018 13:06
Something like this might also be an option:
``````const safeAdd = curry(
(x, y) =>
isNaN(x)
? y
: isNaN(y)
? x
: add(x, y)
)``````
But I'm not 100% sold on the idea of `safeAdd` :)
Ben Briggs
@ben-eb
Dec 02 2018 17:29
``ifElse(isNil, always(identity), unary(add))(2)(undefined) // NaN``

For me this is a good use case for the Maybe type:

``````S.lift2(x => y => x + y) (S.Nothing) (S.Just(3)) // Nothing
S.lift2(x => y => x + y) (S.Just(2)) (S.Just(3)) // S.Just(5)``````

https://sanctuary.js.org/#maybe-type

Ben Briggs
@ben-eb
Dec 02 2018 17:34
^ Or alternately `S.lift2(S.add)`
Kurt Milam
@kurtmilam
Dec 02 2018 18:19
Agreed - this `safeAdd` doesn't look all that safe to me.
Greg Fagan
@gregfagan
Dec 02 2018 22:57
okay thanks y'all.. `safeAdd` was just an example, I forget what my original use case was. I'll have to go back and look later