简体   繁体   中英

Map over an array wrapped in a Maybe

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)

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.

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