I’m trying to do what must be blindingly obvious in Haskell, which is go from Just [1] and Just [2] to Just [1, 2]. However I can’t find anything online as I keep finding related but unhelpful pages. So, how do you achieve this?
I’m trying to do what must be blindingly obvious in Haskell, which is go
Share
You can use
liftA2 (++):liftA2just lifts a binary function into anApplicative.Applicatives were designed for lifting functions of arbitrary arguments in a context, so they’re perfect for this. In this case, theApplicativewe’re using isMaybe. To see how this works, we can look at the definition:(<$>)just lifts any function on pure values to one operating insidef:(a -> b) -> f a -> f b. (It’s just an alias forfmap, if you’re familiar withFunctors.) ForMaybe:(<*>)is a bit trickier: it applies a function insidefto a value insidef:f (a -> b) -> f a -> f b. ForMaybe:(In fact,
f <$> xis the same thing aspure f <*> x, which isJust f <*> xforMaybe.)So, we can expand the definition of
liftA2 (++):Indeed, we can use these operators to lift a function of any number of arguments into any
Applicative, just by following the pattern ofliftA2. This is called applicative style, and is very common in idiomatic Haskell code. In this case, it might even be more idiomatic to use it directly by writing(++) <$> a <*> b, ifaandbare already variables. (On the other hand, if you’re partially applying it — say, to pass it to a higher-order function — thenliftA2 (++)is preferable.)Every
Monadis anApplicative, so if you ever find yourself trying to “lift” a function into a context,Applicativeis probably what you’re looking for.