2

How do I map over an array wrapped in a Maybe or any other Monad? Right now I'm using

const map2 = curry(
  (fn, xs) => map(map(fn))(xs)
)
const data = [1, 2]
pipe(
  Maybe, 
  map2(add(1))
)(data)
jgr0
  • 697
  • 2
  • 6
  • 20
  • 1
    With `map` you are actually using the functor instance of `Maybe`, not the monadic one. Do you recognize this pattern `map(map(fn))`? It's merely function composition. So alternatively you can do something like `comp(map, map) (fn)` (which is probably more clear semantically then `map2`), but I don't know if this works with Ramda's way of currying. –  Jun 29 '17 at 11:03
  • It indeed does work with Ramda. But since I will be putting arrays a lot of times inside a Monad (Either / Maybe), I guess I'll use map2 to avoid repetition. Can I implement map2 using lift? – jgr0 Jun 29 '17 at 11:25
  • 1
    No. `map` is already a lift operation, hence there are only the arity-sepcific `liftA` and `liftM` for applicatives and monads respectively. –  Jun 29 '17 at 12:03
  • @ftor: Ramda is built on the much more weakly typed JS, and it doesn't supply such constructs as `liftA2` or `liftM3`. Instead it supplies only `liftN`, which lifts a function operating on `n` values into one operating on `n` *containers* of values, and the gloss `lift`, which does the same thing, but uses the reported arity of the function. – Scott Sauyet Jun 29 '17 at 12:43
  • I think your `map2` is fine, although I might look for a more descriptive name if possible. – Scott Sauyet Jun 29 '17 at 12:47
  • @ScottSauyet Thanks Scott, I keep that in mind. –  Jun 29 '17 at 13:01

1 Answers1

0

Its hard to know because it isnt clear why you need to wrap the array in a maybe. Is it the array that may be absent or the values in the array? Because you want to map over the array it seems like the values in the array may be absent, in which case you really want an array of maybes.

Essentially your solution is the correct way to map twice but this is seldom required when working with adts.

One thing that occurs to me immediately is to fold the maybe of list with a default value of an empty array and then just map over that normally. The take away is that when you find yourself needing to map twice you should probably try to reformulate your approach.

Alfred Young
  • 397
  • 1
  • 3
  • 15