Skip to content

Instantly share code, notes, and snippets.

@etorreborre
Created August 3, 2010 02:47
Show Gist options
  • Save etorreborre/505743 to your computer and use it in GitHub Desktop.
Save etorreborre/505743 to your computer and use it in GitHub Desktop.
/** I think it's better if we can define replaceFirst generally on Iterables */
def replaceFirst[T](it: Iterable[T], predicate:T=>Boolean, f:T=>T): Iterable[T] = {
if (it.isEmpty) it
else if (predicate(it.head)) it.take(1) .map(f) ++ it.tail
else it.take(1) ++ replaceFirst(it.tail, predicate, f)
}
/**
* Otherwise on Lists, that can be fun to use a foldLeft.
* It's a bit ugly though with the trailing _2
*/
def alwaysTrue[T] = (t: T) => true
def replaceFirst2[T](it: List[T], predicate:T=>Boolean, f:T=>T): List[T] = {
it.foldLeft((predicate, List[T]())) { case ((p, res), current) =>
if (p(current))
(alwaysTrue, f(current) :: res)
else
(predicate, current :: res)
}._2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment