Skip to content
This repository was archived by the owner on Dec 22, 2021. It is now read-only.
This repository was archived by the owner on Dec 22, 2021. It is now read-only.

Have some sort of HasBuilder type class ? #65

@nrinaudo

Description

@nrinaudo

Is there any chance to have some sort of type class that would provide features similar to:

trait HasBuilder[F[_]] {
  def newBuilder[A]: Builder[A, F[A]]
}

With default instances for all applicable collection types?

I know of at least one concrete use case: type class based decoding libraries. Let's take the example of a very simple CSV decoding library. One would write decoding type class as follows:

// Decodes a single CSV cell
trait CellDecoder[A] {
  def decode(cell: String): Try[A]
}

// Decode an entire CSV row
trait RowDecoder[A] {
  def decode(row: Seq[String]): Try[A]
}

With CanBuildFrom, it's easy to provide an instance of RowDecoder for all collection types:

implicit def cbfDecoder[A, F[_]](implicit da: CellDecoder[A], cbf: CanBuildFrom[Nothing, A, F[A]]): RowDecoder[F[A]] = new RowDecoder[F[A]] {
  override def decode(row: Seq[String]): (row.foldLeft(Success(cbf.apply())) { (acc, cell) => 
    for {
      builder <- acc
      a <- da.decode(cell)
    } yield builder += a).map(_.result())
}

I know of at least three libraries that use this mechanism:

I understand CanBuildFrom is going to disappear, and no mechanism is planned to emulate the above behaviour. The HasBuilder type class I'm suggesting would replace it, and is vastly simpler (and less tied to the core implementation of the collection API) than CBF.

It would ideally be part of the standard collection API, although I can't think of anything that would prevent third party libraries from providing that feature externally.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions