@lyrical_logical
val increment: Int => Int = n => n + 1
val double: Int => Int = n => n * 2
val composed = double.compose(increment)
// or increment.andThen(double)
composed(10) // => 22
object Calculator extends RegexParsers {
def number = """\d+(\.\d*)?""".r ^^ { _.toDouble }
def factor = number | "(" ~> expr <~ ")"
def term = factor ~ rep( "*" ~ factor | "/" ~ factor) ^^ {
case number ~ list => ...
}
def expr = term ~ rep("+" ~ term | "-" ~ term) ^^ {
case number ~ list => ...
}
}
// complex
def complexFunction(s: String, n: Int): Int => Unit
// trivial
def identity[T](t: T): T
someFunction.compose(identity)
class LogRetriever {
// hard wiring
val auth = new OAuth2Authorizer
val logApi = new LogApi
def retrieve() = {
auth.autorize match {
case Success(token) => logApi.getLatests(token)
case Failure => ...
}
}
}
class LogRetriever(auth: OAuth2Authorizer, logApi: LogApi) {
def retrieve() = {
auth.autorize match {
case Success(token) => logApi.getLatests(token)
case Failure => ....
}
}
}
new LogRetriever(new OAuth2Authorizer, new LogApi)
class LogRetriever(auth: OAuth2Authorizer, logApi: LogApi) {
def retrieve() = {
auth.autorize match {
case Success(token) => logApi.getLatests(token)
case Failure => ....
}
}
}
new LogRetriever(new OAuth2Authorizer, new LogApi)
class LogRetriever {
this: {
type Token
def authorize(): Token
def getLatests(token: Token): Seq[String]
} =>
def retrieve() = {
autorize() match {
case Success(token) => getLatests(token)
case Failure => ....
}
}
}
new LogRetriever extends OAuth2Authorizer with LogApi
class SomeClass { this: {
type T // implementation hiding
} =>
// implemented by T
// but SomeClass doesn't needs know about T
}
Correspondences
Correspondences(signature)
trait Validator {
type T
def validate(t: T): Boolean
}
// normally, use generics in Scala
trait Validator[T] {
def validate(t: T): Boolean
}
module type Validator = sig
type t
val validate: t -> bool
end
Correspondences(module)
object Configuration {
val credential = ...
val loggerName = ...
}
module Configuration = struct
val credential = ...
val loggerName = ...
end
Correspondences(functor)
trait IntHashMap {
self: {
type T
def hash(n: Int): Int
} =>
def get(k: Int): T = ...
def insert(k: Int, v: T): T = ...
}
// need instantiation
new IntHashMap extends Details
module IntHashSet (
M: sig
type t
val hash: int -> int
end
) = struct
let get k = ...
let insert kv = ...
end
がっこうぐらし!三巻より引用