optics-dev / optics-dev/Monocle

Shall we base Foldable on `Iterator`?

Open
#1,013 3 comments 2 reactions 1 assignee View on GitHub

@yilinwei is already working on this.

Since Jan 3, 2024.

breaking
Dominant language
Scala
Stars
1.7k
Forks
207
Avg merge
7h 59m
Merged PRs (30d)
5

Description

Currently Fold is based on foldMap

trait Fold[S, A] {
  def foldMap[M: Monoid](f: A => M)(s: S): M
}

The problem is that foldMap is not lazy, so when we use foldMap to implement headOption or find, we need to traverse the entire dataset.

val list = List(1, 2, 3, 4)
var counter = 0

val result = Fold.fromFoldable[List, Int].foldMap{x => counter +=1; Option(x)}(list)(Monoids.firstOption)

assertEquals(result, Some(1))
assertEquals(counter, 4)

counter is equal to 4, we traverse the entire list.

An alternative encoding could be based on Iterator which would allow a simple and lazy implementation for headOption, find, and so on.

trait Fold[S, A] { self =>
  def iterator(from: S): Iterator[A]

  def andThen[B](other: Fold[A, B]): Fold[S, B] = new Fold[S, B] {
    def iterator(from: S): Iterator[B] = self.iterator(from).flatMap(other.iterator)
  }
}

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.