Last active
August 29, 2015 14:25
-
-
Save tonymorris/079acde48ff5c9180b57 to your computer and use it in GitHub Desktop.
Fold exercises in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait MyOption[A] { | |
def fold[B](n: => B, s: A => B): B | |
// Define the usual Option API. | |
// | |
// * Constructors (on the object) | |
// some | |
// none | |
// * methods | |
// map | |
// flatMap | |
// orElse | |
// getOrElse | |
// any other useful functions | |
} | |
trait MyEither[A, B] { | |
def fold[X](left: A => X, right: B => X): X | |
// Define the usual Either API. | |
// | |
// * Constructors (on the object) | |
// left | |
// right | |
// * methods | |
// map | |
// flatMap | |
// orElse | |
// getOrElse | |
// any other useful functions | |
} | |
trait MyList[A] { | |
def fold[B](b: B, f: (A, B) => B): B // aka foldRight | |
// Define the usual List API. | |
// | |
// * Constructors (on the object) | |
// nil | |
// cons | |
// * methods | |
// map | |
// flatMap | |
// foldLeft | |
// filter | |
// reverse | |
// append | |
// any other useful functions | |
} | |
trait Semigroup[A] { | |
def op[A](a1: A, a2: A): A | |
} | |
trait Monoid[A] extends Semigroup[A] { | |
def id[A]: A | |
} | |
trait MyList2[A] { | |
def fold[B: Monoid](f: A => B): B | |
// Define the usual List API. | |
// | |
// * Constructors (on the object) | |
// nil | |
// cons | |
// * methods | |
// map | |
// flatMap | |
// foldLeft | |
// filter | |
// reverse | |
// append | |
// any other useful functions | |
} | |
trait NonEmptyList[A] { | |
def fold[B: Semigroup](f: A => B): B | |
// Define a NonEmptyList API. | |
// | |
// * Constructors (on the object) | |
// single | |
// cons | |
// * methods | |
// map | |
// flatMap | |
// foldLeft | |
// reverse | |
// append | |
// any other useful functions | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment