Skip to content

Instantly share code, notes, and snippets.

View globulon's full-sized avatar
💭
I may be slow to respond.

patterngazer globulon

💭
I may be slow to respond.
View GitHub Profile
@globulon
globulon / Function Functor.scala
Created February 23, 2012 10:56
Function Functor
//Function type being
(A) ⇒ T
//we apply
(T) ⇒ U
//the returned type will be
(A) ⇒ U
def map[T, U](source: (A) ⇒ T)(f: (T) ⇒ U): (A)⇒ U
@globulon
globulon / Function Functor map.scala
Created February 23, 2012 11:05
Function Functor map implementation
def map[T, P >: T, U](source: (A) ⇒ T)(f: (P) ⇒ U): (A)⇒ U = f.compose(source)
@globulon
globulon / Function Functor map alternate.scala
Created February 23, 2012 11:11
Function Functor map alternate
def map[T, P >: T, U](source: (A) ⇒ T)(f: (P) ⇒ U): (A)⇒ U = (x: A) ⇒ f(source(x))
@globulon
globulon / Function Monad.scala
Created February 23, 2012 11:24
Function Monad
def apply[T](data: T): (A) ⇒ T = ( _ ⇒ data)
def flatten[T](m: (A) ⇒ (A) ⇒ T): (A) ⇒ T = (x: A) ⇒ m(x)(x)
@globulon
globulon / Function Applicative Functor.scala
Created February 23, 2012 11:57
Function Applicative Functor
case class FunctionApplicative[A]() extends Applicative[({type λ[α] = Function[A,α]})#λ]{
def apply[T](data: T): (A) ⇒ T = ( _ ⇒ data)
def flatten[T](m: (A) ⇒ (A) ⇒ T): (A) ⇒ T = (x: A) ⇒ m(x)(x)
def map[T, P >: T, U](source: (A) ⇒ T)(f: (P) ⇒ U): (A)⇒ U = f.compose(source)
}
@globulon
globulon / FAF canonical.scala
Created February 23, 2012 12:07
Function Applicative Functor canonical example
def `*2` = (x: Int) ⇒ x * 2
def `+10` = (x: Int) ⇒ 10 + x
println((for {
a ← `*2`
b ← `+10`
} yield (a + b))(3))
//produces 19
case class Config[T](data: T)
implicit object ApplicativeConfig extends Applicative[Config] {
def apply[T](data: T) = Config(data)
def flatten[T](m: Config[Config[T]]) = m.data
def map[T, P >: T, U](source: Config[T])(f: (P) => U) = Config(f(source.data))
}
@globulon
globulon / sequence.scala
Created March 4, 2012 18:44
Sequence defintion
def sequence[T, A[_]](input: List[A[T]])(implicit applicative: Applicative[A]): A[List[T]] = {
import applicative._
input match {
case (x :: xs) ⇒
def cons(head: T, list: List[T]): List[T] = head :: list
liftA2(cons, x, sequence(xs))
case _ ⇒ pure(List.empty[T])
}
}
trait Traverse[C[_]] {
def traverse[M[_], T, U](source: C[T])(f: (T) ⇒ M[U])(implicit applicative: Applicative[M]): M[C[U]]
final def sequence[M[_], T](source: C[M[T]])(implicit applicative: Applicative[M]): M[C[T]] = {
traverse[M, M[T], T](source){identity}
}
}
@globulon
globulon / Traversable list.scala
Created March 4, 2012 19:17
Traversable list
trait ListLike[C[_]] {
def cons[T](x: T, xs: C[T]): C[T]
def empty[T](): C[T]
def first[T](source: C[T]): Option[T]
def rest [T](source: C[T]): C[T]
}