Created
April 18, 2012 04:01
-
-
Save raymondtay/2411035 to your computer and use it in GitHub Desktop.
Simple Functor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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