Created
August 3, 2010 02:47
-
-
Save etorreborre/505743 to your computer and use it in GitHub Desktop.
This file contains 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
/** 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