Last active
August 29, 2015 14:21
-
-
Save beala/186973544471aa0caf86 to your computer and use it in GitHub Desktop.
NonEmptyList
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 Main { | |
// NonEmpty because the constructor forces you to provide at least one | |
// instance of A. | |
case class NonEmptyList[A](a: A, as: List[A]) { | |
def map[B](f: A => B): NonEmptyList[B] = { | |
NonEmptyList[B](f(a), as.map(f)) | |
} | |
def flatMap[B](f: A => NonEmptyList[B]): NonEmptyList[B] = flatten(map(f)) | |
} | |
def flatten[A](nel: NonEmptyList[NonEmptyList[A]]): NonEmptyList[A] = { | |
val NonEmptyList(NonEmptyList(h, hs), as) = nel | |
val bs = as.flatMap{case NonEmptyList(x, xs) => x :: xs} | |
NonEmptyList(h, hs ++ bs) | |
} | |
def run(): Unit = { | |
val original = NonEmptyList(1, List(2,3,4)) | |
// Multiply all elements by 2. | |
val doubled = original.map(x => x * 2) | |
// Use flatMap to duplicate each element. | |
val duplicated = original.flatMap(x => NonEmptyList(x, List(x))) | |
println(s"Original: $original") | |
println(s"Doubled: $doubled") | |
println(s"Duplicated: $duplicated") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: