Skip to content

Instantly share code, notes, and snippets.

@raymondtay
Created April 18, 2012 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raymondtay/2411035 to your computer and use it in GitHub Desktop.
Save raymondtay/2411035 to your computer and use it in GitHub Desktop.
Simple Functor
// Functors appear to be type converters for type constructors
trait Functor[T[_]] {
def apply[A](x: A) : T[A]
def map[A,B](x: T[A])(f: A => B) : T[B]
}
// Simple Demo with Functors
object FunctorDemo extends App {
val listInt = List(1,2,3,4,5,6)
// In this simple example, i'm trying to convert a list of 'Int's
// to a list of 'Double's. The key function is the 'map' where it
// transform a type of 'Int' to 'Double'
val converter = new Functor[List] {
def apply[Double](x: Double) : List[Double] = List(x)
def map[Int, Double](x: List[Int])(f: Int => Double) : List[Double] = {
for (i <- x ) yield f(i)
}
}
val listDouble = converter.map(listInt)(_.toDouble)
println("We're going to convert a list of 'int' to list of 'double'")
println("before -> " + listInt)
println("after -> " + listDouble)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment