Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to sum a list of Maybe Int in haskell

Tags:

haskell

Is there a more idiomatic way to implement the following? I feel like I'm missing a way to get rid of the lambda, but couldn't figure out a way to convert it to point-free. Maybe there is another non-applicative way as well that is more straight forward?

import Data.Maybe
import Control.Applicative

foldl (\x y -> pure (+) <*> x <*> y) (Just 0) [Just 3, Just 4]
-- Just 7

foldl (\x y -> pure (+) <*> x <*> y) (Just 0) [Just 3, Just 4, Nothing]
-- Nothing
like image 831
Xavier Shay Avatar asked Nov 17 '13 18:11

Xavier Shay


Video Answer


1 Answers

I'd just use sequence from Control.Monad:

> fmap sum $ sequence [Just 3, Just 4]
Just 7
> fmap sum $ sequence [Just 3, Just 4, Nothing]
Nothing

For the point-free form:

sumMaybe :: Num a => [Maybe a] -> Maybe a
sumMaybe = fmap sum . sequence
like image 73
bheklilr Avatar answered Oct 18 '22 02:10

bheklilr