Last active
December 15, 2015 03:28
-
-
Save tpolecat/5194027 to your computer and use it in GitHub Desktop.
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
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