scala - Why does scalaz's implementation of Monoid for Option evaluate the f2 function twice? -
the definition of scalaz's option monoid follows:
implicit def optionmonoid[a: semigroup]: monoid[option[a]] = new monoid[option[a]] { def append(f1: option[a], f2: => option[a]) = (f1, f2) match { case (some(a1), some(a2)) => some(semigroup[a].append(a1, a2)) case (some(a1), none) => f1 case (none, some(a2)) => f2 case (none, none) => none } def zero: option[a] = none }
f2
pass name param means each call evaluate expression. why should evaluated again when evaluated in pattern match? returning some(a2)
should same result , expression f2
expensive.
am missing something?
it looks me written highlight symmetry of problem , clarity, not speed. can't drop laziness of second argument since semigroup
defines way, , in other contexts times laziness of second argument may essential. preserve visual representation of symmetry of problem, want add
val g2 = f2 // force evaluation (f1, g2) match { ...
or somesuch.
(it nice if name arguments called lazy automatically memoize them.)
Comments
Post a Comment