Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
import scalaz._, Scalaz._
object Main extends App {
case class Wheat()
case class Flour()
case class Dough()
case class Bread()
type Result[T] = String \/ T
type Log[T] = WriterT[Result, Vector[String], T]
def write(s: String): Log[Unit] = WriterT.writerT(\/-(Vector(s) -> ()))
def grind(w: Wheat): Log[Flour] = for {
_ <- write("make the flour")
} yield Flour()
def kneadDough(f: Flour): Log[Dough] = for {
_ <- write("make the dough")
} yield Dough()
def distributeDough(d: Dough): Log[Seq[Dough]] = for {
_ <- write("distribute the dough")
} yield Seq[Dough]()
def bake(temperature: Int, duration: Int, sd: Seq[Dough]): Log[Seq[Bread]] = for {
_ <- write(s"bake the bread, duration: $duration, temperature: $temperature")
} yield Seq[Bread]()
val bakeRecipe1 = (bake _).curried(350)(45)
val result = grind(Wheat()) >>= kneadDough >>= distributeDough >>= bakeRecipe1
result.run match {
case -\/(e) => println(s"Error: $e")
case \/-((log, res)) => log foreach println
}
}
// результат тот же:
// make the flour
// make the dough
// distribute the dough
// bake the bread, duration: 45, temperature: 350
При всей моей любви к scala, композиция в ней сделана отвратно. Поэтому, в своей библиотечке я добавил следующий синтаксис для композиции:
implicit class EnrichedFunction[-A,+B](f: A => B) {
/**
* Shortcut for function composition
* @return a composition of functions
*/
def o [R] (g: R => A): R => B = x => f(g(x))
def ∘ [R] (g: R => A): R => B = x => f(g(x))
}Собственно, делает то же самое что и compose (можете сравнить код), однако, по моему-мнению выглядит более юзабельно.
Композиция функций на F# и Scala