0
\$\begingroup\$

I wrote this code to append Maybe's:

ghci> (:) <$> Just 5 <*> ((:) <$> Just 100 <*> Just [])
Just [5,100]

Similarly:

ghci> (:) <$> Just 5 <*> ( (:) <$> Just 10 <*> ((:) <$> Just 100 <*> Just []) )
Just [5,10,100]

Is this code idiomatic? Perhaps there's a more concise way to append a bunch of Maybe's together?

\$\endgroup\$
3
  • \$\begingroup\$ What is the actual code this situation risen? Why not just write Just [5,10,100]? \$\endgroup\$ Commented Dec 4, 2014 at 6:57
  • \$\begingroup\$ Just curious how to do it with <*>. No real purpose other than curiosity. \$\endgroup\$ Commented Dec 8, 2014 at 3:10
  • \$\begingroup\$ W.r.t. difference between sequence and concatMap maybeToList: sequence [Just 1, Nothing, Just 2] is Nothing; whereas concatMap maybeToList [Just 1, Nothing, Just 2] is [1, 2]. \$\endgroup\$ Commented Dec 8, 2014 at 11:15

2 Answers 2

5
\$\begingroup\$

Well, while the code surely works, it does look ugly. I would suggest something like this:

sequence [Just 5, Just 10, Just 100]

or, if you really want to use Applicatives instead of Monads,

sequenceA [Just 5, Just 10, Just 100]

from Data.Traversable.

\$\endgroup\$
1
\$\begingroup\$

And if you want to use neither Monad nor Applicative you can just use concatMap maybeToList from Data.Maybe.

\$\endgroup\$
1
  • \$\begingroup\$ Minor point: It should be concatMap maybeToList instead of concatMap . maybeToList. \$\endgroup\$ Commented Dec 8, 2014 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.