首页 > 解决方案 > 无法理解 flatMap 如何消除 Nil 元素

问题描述

我正在阅读 Scala 中的函数式编程一书,在数据结构一章的末尾,您被要求filter根据flatMap. 以下是必要的功能和实现:

sealed trait List[+A]

case object Nil extends List[Nothing]

case class Cons[+A](head: A, tail: List[A]) extends List[A]

object List {
  def apply[A](as: A*): List[A] = {
    if (as.isEmpty) Nil
    else Cons(as.head, apply(as.tail: _*))
  }

  def append[A](l1: List[A], l2: List[A]): List[A] = {
    foldRight(l1, l2)((elem, acc) => Cons(elem, acc))
  }

  def concat[A](ls: List[List[A]]): List[A] = {
    foldLeft(ls, Nil: List[A])(append)
  }

  def map[A, B](l: List[A])(f: A => B): List[B] = {
    foldRight(l, Nil: List[B])((elem, acc) => Cons(f(elem), acc))
  }

  def filter[A](l: List[A])(f: A => Boolean): List[A] = {
    List.flatMap(l)(a => if (f(a)) List(a) else Nil)
  }

  def flatMap[A, B](l: List[A])(f: A => List[B]): List[B] = {
    concat(map(l)(f))
  }

  def foldRight[A, B](l: List[A], z: B)(f: (A, B) => B): B = {
    l match {
      case Nil => z
      case Cons(h, t) => f(h, foldRight(t, z)(f))
    }
  }

  def foldLeft[A, B](l: List[A], z: B)(f: (B, A) => B): B = {
    l match {
      case Nil => z
      case Cons(h, t) => foldLeft(t, f(z, h))(f)
    }
  }
}

实际的函数调用在这里:

val x = List(1, 2, 3, 4, 5)

List.filter(x)(_ < 3)

据我所知,在映射步骤之后,您将拥有一个如下所示的列表: Cons(Cons(1, Nil), Cons(2, Nil), Cons(Nil, Nil)...

我无法查看Nil从最终结果中过滤掉的元素的位置。

标签: scalafunctional-programming

解决方案


它们没有被“过滤掉”。在您应用到列表列表后,它们就会消失concat,因为与空列表的连接没有任何作用。


推荐阅读