Skip to content

Instantly share code, notes, and snippets.

@songpp
Created January 27, 2013 04:56
Show Gist options
  • Select an option

  • Save songpp/4646440 to your computer and use it in GitHub Desktop.

Select an option

Save songpp/4646440 to your computer and use it in GitHub Desktop.
Functor
package sun.flower.category
/**
*
* User: sunflower
* Date: 13-1-26
* Time: 下午4:02
*
*/
object Category{
//def id[A](a: A) = a // map is functions
trait Category[-->[_,_]]{
def id[A] : A --> A
def compos[A,B,C](f: A => B, g : B => C) : A --> C
}
class MyCategory extends Category[Function]{
def id[A]: A => A = a => a
def compos[A,B,C]( f : A => B, g : B => C ) : A => C = g compose f
}
def main(args: Array[String]) {
}
}
package sun.flower.category
/**
*
* User: sunflower
* Date: 13-1-26
* Time: 下午4:45
*
*/
object MyFunctors {
trait Functor[-->[_,_], -->>[_,_], F[_]]{
def fmap[A,B](f : A --> B) : F[A] -->> F[B]
}
object Functor{
def fmap[A,B,F[_]](xs : F[A])( f : A => B)(implicit functor : MyFunctor[F]) : F[B] =
functor.fmap(f)(xs)
trait MyFunctor[F[_]] extends Functor[Function,Function,F]
implicit object ListFunctor extends MyFunctor[List]{
def fmap[A,B](f : A => B) : List[A] => List[B] = _ map f
}
implicit object OptionFunctor extends MyFunctor[Option]{
def fmap[A,B](f: A => B) : Option[A] => Option[B] = _ map f
}
}
def main(args: Array[String]) {
println(Functor.fmap(List(1,2,3))( _ + 1 ))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment