Skip to content

Instantly share code, notes, and snippets.

@tpolecat
Last active December 15, 2015 03:28
Show Gist options
  • Save tpolecat/5194027 to your computer and use it in GitHub Desktop.
Save tpolecat/5194027 to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
object FirstDup extends App {
def unfold[A, B](b: B)(f: B => Option[(A, B)]): Stream[A] = f(b) match {
case None => Stream.empty
case Some((a, b)) => a #:: unfold(b)(f)
}
def prefix[A](as: Traversable[A]): Stream[A] =
unfold((as, Set[A]())) {
case (as, acc) =>
as.headOption match {
case Some(a) if acc contains a => None
case Some(a) => Some((a, (as.tail, acc + a)))
case None => None
}
}
println(prefix(List(1, 2, 3, 2, 3)).toList) // List(1, 2, 3)
println(prefix(List(1, 2, 3)).toList) // List(1, 2, 3)
println(prefix(List[Int]()).toList) // List()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment