Skip to content

Instantly share code, notes, and snippets.

@beala
Last active August 29, 2015 14:21
Show Gist options
  • Save beala/186973544471aa0caf86 to your computer and use it in GitHub Desktop.
Save beala/186973544471aa0caf86 to your computer and use it in GitHub Desktop.
NonEmptyList
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")
}
}
@beala
Copy link
Author

beala commented May 14, 2015

Output:

Original: NonEmptyList(1,List(2, 3, 4))
Doubled: NonEmptyList(2,List(4, 6, 8))
Duplicated: NonEmptyList(1,List(1, 2, 2, 3, 3, 4, 4))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment