Skip to content

Instantly share code, notes, and snippets.

@micrypt
Created June 15, 2011 21:27
Show Gist options
  • Select an option

  • Save micrypt/1028166 to your computer and use it in GitHub Desktop.

Select an option

Save micrypt/1028166 to your computer and use it in GitHub Desktop.
Random Scala notes
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
class Comonad w where
(=>>) :: w a -> (w a -> b) -> w b
extract :: w a -> a
// Verbose identity function
def id[A]:Function[A,A] = (a) => a
// Predicates
type Pred[A] = A => Boolean;
val even: Pred[Int] = i => i % 2 == 0;
def not[A]: Pred[A] => Pred[A] = p => !p(_);
val odd = not(even);
odd(10)
// Predicates: alternative
type Pred[A] = A => Boolean;
def even: Pred[Int] = i => i % 2 == 0;
def not[A]: Pred[A] => Pred[A] = p => !p(_);
val odd = not(even);
odd(10)
// BinaryIsTraversable
def BinaryTreeIsTraversable[A]: Traversable[BinaryTree] = new Traversable[BinaryTree] {
def createLeaf[B] = (n: B) => (Leaf(n): (BinaryTree[B]))
def createBin[B] = (nl: BinaryTree[B]) => (nr: BinaryTree[B]) => (Bin(nl, nr): BinaryTree[B])
def traverse[F[_]: Applicative, A, B](f: A => F[B]): BinaryTree[A] => F[BinaryTree[B]] =
(t: BinaryTree[A]) => {
val applicative = implicitly[Applicative[F]]
t match {
case Leaf(a) => applicative.apply(applicative.point(createLeaf[B]))(f(a))
case Bin(l, r) =>
applicative.apply(applicative.apply(applicative.point(createBin[B]))(traverse[F, A, B](f).apply(l))).
apply(traverse[F, A, B](f).apply(r))
}
}
}
// >> BinaryTreeIsTraversable: [A]=> Traversable[BinaryTree]
// Pointed and Co-pointed Functors
def point[F[_], A]: A => F[A]; def copoint[F[_], A]: F[A] => A
// CoMonad
trait Comonad[F[_]] extends Functor[F] {
def extract[A]: F[A] => A
def extend(k: F[A] => B): F[A] => F[B]
}
// Scaring the little children
def sum(x: ({type t = List[Int]})#t) = x.sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment