Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Folding across Maybes in Haskell

Tags:

In an attempt to learn Haskell, I have come across a situation in which I wish to do a fold over a list but my accumulator is a Maybe. The function I'm folding with however takes in the "extracted" value in the Maybe and if one fails they all fail. I have a solution I find kludgy, but knowing as little Haskell as I do, I believe there should be a better way. Say we have the following toy problem: we want to sum a list, but fours for some reason are bad, so if we attempt to sum in a four at any time we want to return Nothing. My current solution is as follows:

import Maybe  explodingFourSum :: [Int] -> Maybe Int explodingFourSum numberList =     foldl explodingFourMonAdd (Just 0) numberList     where explodingFourMonAdd =         (\x y -> if isNothing x                     then Nothing                     else explodingFourAdd (fromJust x) y)  explodingFourAdd :: Int -> Int -> Maybe Int explodingFourAdd _ 4 = Nothing explodingFourAdd x y = Just(x + y) 

So basically, is there a way to clean up, or eliminate, the lambda in the explodingFourMonAdd using some kind of Monad fold? Or somehow currying in the >>= operator so that the fold behaves like a list of functions chained by >>=?

like image 729
janders Avatar asked Sep 18 '11 20:09

janders


1 Answers

I think you can use foldM

explodingFourSum numberList = foldM explodingFourAdd 0 numberList 

This lets you get rid of the extra lambda and that (Just 0) in the beggining.


BTW, check out hoogle to search around for functions you don't really remember the name for.

like image 167
hugomg Avatar answered Oct 04 '22 01:10

hugomg