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

Scala example source code file (Align.scala)

This example Scala source code file (Align.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

align, alignlaw, boolean, functorlaw, option, semigroup

The Align.scala Scala example source code

package scalaz

////
/**
 *
 */
////
trait Align[F[_]] extends Functor[F] { self =>
  ////

  import \&/._

  def alignWith[A, B, C](f: A \&/ B => C): (F[A], F[B]) => F[C]

  def product[G[_]](implicit G0: Align[G]): Align[λ[α => (F[α], G[α])]] = new ProductAlign[F, G] {
    implicit def F = self

    implicit def G = G0
  }

  def align[A, B](a: F[A], b: F[B]): F[A \&/ B] =
    alignWith[A, B, A \&/ B](identity)(a, b)

  def padWith[A, B, C](f: (Option[A], Option[B]) => C): (F[A], F[B]) => F[C] =
    alignWith(t => {
      val (a, b) = t.pad
      f(a, b)
    })

  def pad[A, B]: (F[A], F[B]) => F[(Option[A], Option[B])] =
    padWith((a, b) => (a, b))

  def merge[A](a1: F[A], a2: F[A])(implicit S: Semigroup[A]): F[A] =
    alignWith[A, A, A](t => \&/.merge(t))(a1, a2)

  def alignSwap[A, B](a: F[A], b: F[B]): F[B \&/ A] =
    alignWith[A, B, B \&/ A](_.swap)(a, b)

  def alignA[A, B](a: F[A], b: F[B]): F[Option[A]] =
    alignWith[A, B, Option[A]](_.a)(a, b)

  def alignB[A, B](a: F[A], b: F[B]): F[Option[B]] =
    alignWith[A, B, Option[B]](_.b)(a, b)

  def alignThis[A, B](a: F[A], b: F[B]): F[Option[A]] =
    alignWith[A, B, Option[A]](_.onlyThis)(a, b)

  def alignThat[A, B](a: F[A], b: F[B]): F[Option[B]] =
    alignWith[A, B, Option[B]](_.onlyThat)(a, b)

  def alignBoth[A, B](a: F[A], b: F[B]): F[Option[(A, B)]] =
    alignWith[A, B, Option[(A, B)]](_.onlyBoth)(a, b)

  trait AlignLaw extends FunctorLaw {
    def collapse[A](a: F[A])(implicit E: Equal[F[A \&/ A]]): Boolean =
      E.equal(map(a)(x => Both(x, x): A \&/ A), align(a, a))
  }

  def alignLaw = new AlignLaw {}

  ////
  val alignSyntax = new scalaz.syntax.AlignSyntax[F] { def F = Align.this }
}

object Align {
  @inline def apply[F[_]](implicit F: Align[F]): Align[F] = F

  ////

  ////
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala Align.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.