Is there a function in scala or scalaz to apply a function to a list if the list is not empty?

StackOverflow https://stackoverflow.com/questions/18553911

  •  26-06-2022
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Without using Scalaz you can also do one of the following:

  • Option(list).filterNot(_.isEmpty).map(f)
  • list match { case x@(_ :: _) => Some(f(x)); case _ => None }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top