Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

scalaz

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.

like image 682
tksfz Avatar asked Feb 16 '23 10:02

tksfz


1 Answers

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.

like image 60
cmbaxter Avatar answered Apr 27 '23 20:04

cmbaxter