Instantly share code, notes, and snippets.

Embed
What would you like to do?
val x = List(1, 2, 3)
val y = 1 :: 2 :: 3 :: Nil
println(x)
println(y)
def sum(list: List[Int]): Int = list match {
case Nil => 0
case n :: rest => n + sum(rest)
}
def multiply(list: List[Int]): Int = list match {
case Nil => 1
case n :: rest => n * multiply(rest)
}
println(sum(x))
println(multiply(y))
def listToString(list: List[String]): String = list match {
case s :: rest => s + " " + listToString(rest)
case Nil => ""
}
val fruits = "Apples" :: "Bananas" :: "Oranges" :: Nil
// println(listToString(y)) // compile error
println(listToString(fruits))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment