Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Set to cats.data.NonEmptySet?

Is there an extension method in cats for the standard Set which converts it to Option[cats.data.NonEmptySet]?

like image 416
Midiparse Avatar asked Feb 01 '19 14:02

Midiparse


1 Answers

Not for scala.collection.immutable.Set, but for SortedSet:

scala> import cats.syntax.set._
import cats.syntax.set._

scala> import scala.collection.immutable.SortedSet
import scala.collection.immutable.SortedSet

scala> SortedSet(1, 2, 3).toNes
res0: Option[cats.data.NonEmptySet[Int]] = Some(TreeSet(1, 2, 3))

You can of course convert an ordinary Set:

scala> Set(1, 2, 3).to[SortedSet].toNes
res1: Option[cats.data.NonEmptySet[Int]] = Some(TreeSet(1, 2, 3))

Cats's NonEmptySet isn't built on Set (and Cats doesn't provide syntax for Set) because Set relies on universal equality to determine what counts as uniqueness for its elements. SortedSet on the other hand requires a scala.math.Ordering instance, which makes it more aligned with the design principles followed in Cats (see e.g. this issue for more discussion).

like image 71
Travis Brown Avatar answered Nov 08 '22 02:11

Travis Brown