gpt4 book ai didi

Scala:以简单的自定义类型实现 map 和 withFilter

转载 作者:行者123 更新时间:2023-12-04 01:05:34 25 4
gpt4 key购买 nike

我正在学习 Scala,并且已经不得不发现单子(monad)的概念对于我目前的知识水平来说有点过于复杂。但是,我的目标至少是创建一个可以与 for 一起使用的非常简单的类。表达式和另外一个过滤器。

根据我的理解,以下规则适用:

  • 为了在 for 表达式的生成器中使用自定义类型(生成器只生成简单变量),它需要实现 map .
  • 如果还需要使用过滤器,那么类型也必须实现 withFilter .

  • 我的最小类如下所示:
    class Grid(private val fields: IndexedSeq[Field])

    class Field(val name: String, val isVisible: Boolean)

    我想要实现的是能够做到以下几点:
    for(f <- grid) yield f.name // needs map
    for(f <- grid; if f.isVisisble) yield f.name // needs map + withFilter

    但是,我很难找到具有这种简单性的示例。如果解决方案是针对上面显示的两个类“量身定制”的,而不是可以应用于任何类的通用解决方案,那就可以了。理解这个简单示例的实现肯定会对我有所帮助。任何帮助表示赞赏,谢谢。

    编辑:

    正如 Lee 所指出的,我的意图似乎只适用于泛型类型。我想如果我忘记类 Field 会更有意义。并重新定义 Grid如下:
    class Grid[E](private val fields: IndexedSeq[E])

    最佳答案

    在这种情况下,您只需传递 map访问包装好的系列fields .
    对于 withFilter您可以调用filter fields上的方法,但我认为这并不完全符合 withFilter 的语义。应该有。

    case class Grid[E](private val fields: IndexedSeq[E]) {
    def map[R](f: E => R): Grid[R] = new Grid(fields map f)
    def withFilter(p: E => Boolean): Grid[E] = new Grid(fields filter p)
    }

    您所要求的更正确但更复杂的实现是:
    case class Grid[E](private val fields: IndexedSeq[E]) {
    def map[R](f: E => R): Grid[R] = new Grid(fields map f)
    def withFilter(p: E => Boolean): WithFilter = new WithFilter(p)

    class WithFilter(p: E => Boolean) {
    def map[R](f: E => R): Grid[R] = new Grid(fields.withFilter(p).map(f))
    def withFilter(q: E => Boolean): WithFilter = new WithFilter(x => p(x) && q(x))
    }
    }

    这样, withFilter将工作 lazily正如预期的那样。

    关于Scala:以简单的自定义类型实现 map 和 withFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27938695/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com