Map over an array wrapped in a Maybe

628 views Asked by At

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)
1

There are 1 answers

0
Alfred Young On

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.