Fold exercises in Scala
| 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