Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing a List of Options with Applicative Functors

Tags:

scala

scalaz

I have a List[Option[Int]] and want to sum over it using applicative functors. From [1] I understand that it should be something like the following

import scalaz._
import Scalaz._

List(1,2,3).map(some(_)).foldLeft(some(0))({
    case (acc,value) => (acc <|*|> value){_+_}
})

however I am simply not able to figure out the correct way to write this. I would be glad if somebody could help me with this.

Thank you very much

[1] How to combine Option values in Scala?

Edit

Thanks for all the great answers.

If there is any None in the list, I want it to return None. I am trying to replace Null/Exception with Option/Either and see if I can produce some usable code.

Some function will fill my list and I want to process it further as easy as possible without checking if one of the elements was None. It should work similar as Exceptions, where I don't have to check for it in my function, but let the caller take care of it.

like image 615
Manuel Schmidt Avatar asked Nov 16 '11 05:11

Manuel Schmidt


1 Answers

You don't really need Scalaz for this. You can just flatten the list, which will convert it to List[Int], removing any items that were None. Then you can reduce it:

List(Some(1), None, Some(2), Some(3), None).flatten.reduce(_ + _) //returns 6: Int
like image 134
Dan Simon Avatar answered Oct 29 '22 17:10

Dan Simon