alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (Generator.scala)

This example Scala source code file (Generator.scala) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Scala by Example" TM.

Learn more about this Scala project at its project page.

Java - Scala tags/keywords

foldable, foldlgenerator, foldrgenerator, generator, generators, reducer

The Generator.scala Scala example source code

package scalaz

/**
 * A `Generator[C]` is a container of elements, and which knows how to efficiently apply a [[scalaz.Reducer]]
 * to extract an answer by combining elements. A `Reducer` may supply efficient left-to-right and
 * right-to-left reduction strategies that a `Generator` may avail itself of.
 */
trait Generator[C[_]] {
  def reduce[E, M](r: Reducer[E, M], c: C[E]): M = to(r, r.zero, c)

  def to[E, M](r: Reducer[E, M], m: M, c: C[E]): M = r.append(m, reduce(r, c))

  def from[E, M](r: Reducer[E, M], c: C[E], m: M): M = r.append(reduce(r, c), m)
}

object Generator extends Generators

trait Generators {

  def FoldrGenerator[F[_] : Foldable]: Generator[F] = new Generator[F] {
    override def reduce[E, M](r: Reducer[E, M], c: F[E]): M =
      Foldable[F].foldr(c, r.zero)(a => b => r.cons(a, b))
  }

  def FoldlGenerator[F[_] : Foldable]: Generator[F] = new Generator[F] {
    override def reduce[E, M](r: Reducer[E, M], c: F[E]): M =
      Foldable[F].foldLeft(c, r.zero)((b, a) => r.snoc(b, a))
  }
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala Generator.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.