Created
April 9, 2016 13:01
-
-
Save prassee/f5a5f28184cdb4a2feaf36093339199e to your computer and use it in GitHub Desktop.
fpis practise chapter 3
This file contains hidden or 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
object chapter3 { | |
println("chapter 3") //> chapter 3 | |
import Basket._ | |
val emptyBag = Empty //> emptyBag : Basket.Empty.type = Empty | |
val intBag = Cons[Int](23, Cons[Int](12, Empty))//> intBag : Basket.Cons[Int] = Cons(23,Cons(12,Empty)) | |
// sum(intBag) | |
import Basket.Bag._ | |
val bagInts = Bag(1,2,3) //> bagInts : Basket.Bag[Int] = Cons(1,Cons(2,Cons(3,Empty))) | |
sum(bagInts) //> res0: Int = 6 | |
} | |
object Basket { | |
trait Bag[+A] | |
case object Empty extends Bag[Nothing] | |
case class Cons[A](head: A, tail: Bag[A]) extends Bag[A] | |
object Bag { | |
def apply[A](a: A*): Bag[A] = { | |
if (a.isEmpty) Empty | |
else Cons(a.head, apply(a.tail: _*)) | |
} | |
def sum(bag: Bag[Int]): Int = { | |
bag match { | |
case Empty => 0 | |
case Cons(h, t) => h + sum(t) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment