Created
October 24, 2015 06:01
-
-
Save itang/00a06ab91d0a936609fa to your computer and use it in GitHub Desktop.
List to Map in Scala
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
scala> :paste | |
// Entering paste mode (ctrl-D to finish) | |
def listToMap[T](list: List[T])(init : Map[T,T] = Map[T,T]()): Map[T,T] = list match { | |
case Nil => init | |
case a :: Nil => init | |
case a :: b :: rest => listToMap(rest)( init + (a -> b)) | |
} | |
// Exiting paste mode, now interpreting. | |
listToMap: [T](list: List[T])(init: Map[T,T])Map[T,T] | |
scala> listToMap(List(1,2,3,4)) | |
<console>:12: error: missing arguments for method listToMap; | |
follow this method with `_' if you want to treat it as a partially applied function | |
listToMap(List(1,2,3,4)) | |
^ | |
scala> listToMap(List(1,2,3,4))() | |
res1: Map[Int,Int] = Map(1 -> 2, 3 -> 4) | |
scala> listToMap(List(1,2,3,4,5))() | |
res2: Map[Int,Int] = Map(1 -> 2, 3 -> 4) | |
scala> listToMap(List(1,2,3,4,5,6))() | |
res3: Map[Int,Int] = Map(1 -> 2, 3 -> 4, 5 -> 6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment