Is there a function in scala or scalaz that applies a function to a list if the list is not empty. And otherwise it returns some default value. The function must be applied to the list itself not to the elements of the list. That is, it accomplishes the following:
implicit class RichList[A, M[A] <: Iterable[A]](list: M[A]) {
def convertOrElse[B](fn: M[A] => B, whenEmpty: B) = {
if (!list.isEmpty) fn(list) else whenEmpty
}
}
Example usage: mylist.convertOrElse("prefix " + _.mkString(", "), "")
I recall seeing this somewhere but it may have been in a blog post or some such. I can't seem to find it in scalaz at the moment, but I can't even really find recent scalaz documentation online (that's a different problem :)
I've written my own implicit as you can see, but I hate adding my own implicits when an appropriate scalaz import would do the trick.
You should be able to use the NonEmptyList
functionality from Scalaz like so:
import scalaz._
import Scalaz._
val list = List()
val str = list.toNel.map(_.list.mkString(",")).getOrElse("empty")
println(str)
In my example, you would see the word "empty" get printed out. If you changed the list definition to:
val list = List("foo", "bar")
Then you would see "foo,bar" get printed out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With