scala - scalaz Foldable compose -


i have next code

val listoption: list[option[int]] = list(1.some, none, 2.some) 

i want fold elements, write next code

val result = listx.fold(0.some)((acc, el) => {   (acc, el) match {     case (some(a), some(b)) => some(a + b)     case (some(a), _) => some(a)     case (_, some(b)) => some(b)     case _ => el   } }) println(result.getorelse(0)) // => 3  

this workds fine, see in scalaz sources next tric

val composefold = foldable[list] compose foldable[option] composefold.fold(listoption) // => 3 

but not understand how correct work, , why scalaz not mix methods listoption instance, , differenct between scala fold , scalaz fold

the scalaz fold function uses monoid instance of elements, don't have supply start value , function combine elements.

a monoid has 2 functions zero/empty , append/combine. int :

val intmonoid = new monoid[int] {   def 0 = 0   def append(a: int, b: => int) = + b } 

using monoid[int] can write scalaz fold scala fold :

import scalaz.foldable import scalaz.std.list._ import scalaz.std.anyval._  val numbers = list(1,2,3) foldable[list].fold(numbers)                          // 6 // analogous following scala fold numbers.fold(intmonoid.zero)(intmonoid.append(_,_))   // 6 

we can combine foldable[list] , foldable[option] showed :

import scalaz.std.option._ foldable[list].fold(list(1,2))    // 3  foldable[option].fold(1.some)     // 1 foldable[option].fold(none[int])  // 0  val foldlisto = foldable[list] compose foldable[option] foldlisto.fold(list(1.some, none, 2.some))  // 3 

you can use foldable syntax import , use concatenate or suml/sumr (there fold clashes list.fold , option.fold) :

import scalaz.syntax.foldable._ list(1,2,3).concatenate  // 6 1.some.concatenate       // 1  list(1.some, none, 2.some).concatenate.concatenate  // 3 

instead of specific imports scalaz.std.list._ , scalaz.syntax.foldable._, use uber imports import scalaz._, scalaz._.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -