Why does scalaz's implementation of Monoid for Option evaluate the f2 function twice?

The definition of the scalaz's option monoid is as 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 is a pass by name param which means each call will evaluate the expression. Why should it be evaluated again when it was just evaluated in the pattern match? Returning Some(a2) should be the same result and the expression f2 could be very expensive.

Am I missing something?

Scalaz's Option.scala source

Answers


It looks to me like it was written to highlight the symmetry of the problem and for clarity, not for speed. You can't just drop the laziness of the second argument since Semigroup defines it that way, and in other contexts times the laziness of the second argument may be essential. To preserve the visual representation of the symmetry of the problem, you probably want to just add

val g2 = f2  // Force evaluation
(f1, g2) match { ...

or somesuch.

(It would be nice if by name arguments could be called lazy to automatically memoize them.)


Need Your Help

How to upload files from form to server and store in a new folder

php forms file-upload file-io

I'm having trouble trying to upload files from a form and create a new folder and store those forms.

authlogic validation

ruby-on-rails ruby authlogic

Sorry for stupid question. but do I need to use standart model validation, such as

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.