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

Is there a function in scala or scalaz that applies the function to the list if the list is not empty. Otherwise, it returns some default value. The function should apply to the list itself not to the list items. That is, it does 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 remember seeing it somewhere, but maybe it was on a blog or some such. At the moment I can’t find it in the scalar, but I can’t even find the latest documentation on the scalaz on the Internet (this is another problem :)

I wrote my own implicit, as you can see, but I do not want to add my own implications when the corresponding import of the skalaz will do the trick.

+4
source share
2 answers

You can use the NonEmptyList functionality as follows:

 import scalaz._ import Scalaz._ val list = List() val str = list.toNel.map(_.list.mkString(",")).getOrElse("empty") println(str) 

In my example, you will see that the word "empty" is printed. If you changed the list definition to:

 val list = List("foo", "bar") 

Then you will see that "foo, bar" is being printed.

+6
source

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 }
+2
source

Source: https://habr.com/ru/post/1499972/


All Articles