Skip to content

Instantly share code, notes, and snippets.

Advanced Functional Programming with Scala - Notes

Copyright © 2017 Fantasyland Institute of Learning. All rights reserved.

1. Mastering Functions

A function is a mapping from one set, called a domain, to another set, called the codomain. A function associates every element in the domain with exactly one element in the codomain. In Scala, both domain and codomain are types.

val square : Int => Int = x => x * x
trait Writes[T] {
def writes(o: T): JsValue
}
trait Reads[T] {
def reads(json: JsValue): T
}
trait Format[T] extends Writes[T] with Reads[T]
@drstevens
drstevens / trampolined-state.scala
Last active August 29, 2015 14:02 — forked from travisbrown/trampolined-state.scala
Trampolining the state monad via applicative combinator appears to work
import scalaz._, Scalaz._
def setS(i: Int): State[List[Int], Unit] = modify(i :: _)
val s = (1 to 10000).foldLeft(state[List[Int], Unit](()).lift[Free.Trampoline]) {
case (st, i) => st *> setS(i).lift[Free.Trampoline]
}
s(Nil).run
// Doesn't compile. Good.
def futureInt(): Future[Int] = Future.value(Future.value(1))
// Compiles. Not good. Caller cannot wait on completion of nested future.
def futureUnit(): Future[Unit] = Future.value(Future.value(()))
// Also compiles. Nice convenience, but not worth the cost of the issues
// it might cause (as above), right?
def futureUnit(): Future[Unit] = Future.value(1)
-Dconfig.resource=test.conf -Dlogger.file=test/resources/logback-test.xml
@drstevens
drstevens / gist:4438371
Last active December 10, 2015 13:08 — forked from OleTraveler/gist:4347051
This demonstrates some of the ways to combine scalaz6 Validaitons. It is the result of answers to question http://stackoverflow.com/questions/13961940/chaining-scalaz-validation-functions-function1a-validatione-b. See answers for more, including combining functions using Kliesi in scalaz6 and scalaz7.
def allDigits: (String) => ValidationNEL[String, String]
def maxSizeOfTen: (String) => ValidationNEL[String, String]
def toInt: (String) => ValidationNEL[String, Int]
val validInt: String => ValidationNEL[String, Int] = s =>
for {
validStr <- (allDigits(s) |@| maxSizeOfTen(s))((_,x) => x)
i <- toInt(validStr)