【问题标题】:Omit input data of map function in Scala在Scala中省略map函数的输入数据
【发布时间】:2015-08-24 15:14:34
【问题描述】:

我正在学习 Spark 源代码,对以下代码感到困惑:

/**
 * Return a new RDD containing the distinct elements in this RDD.
 */
def distinct(numPartitions: Int)(implicit ord: Ordering[T] = null): RDD[T] =
  map(x => (x, null)).reduceByKey((x, y) => x, numPartitions).map(_._1)

map(x => (x, null)) 函数的输入数据是什么?为什么以及何时可以省略输入?

更新:

这里是源代码的link

【问题讨论】:

  • 链接到源代码?
  • 嗨@Daenyth 感谢您的提醒,我已经添加了源代码的链接。

标签: scala apache-spark scala-collections scala-2.10


【解决方案1】:

distinctmap 都是 RDD 类 (source) 上的方法,所以 distinct 只是在同一个 RDD 上调用另一个方法。

map 函数是一个高阶函数 - 即它接受一个函数作为其参数之一 (f: T => U)

/**
 * Return a new RDD by applying a function to all elements of this RDD.
 */
def map[U: ClassTag](f: T => U): RDD[U] = withScope {
  val cleanF = sc.clean(f)
  new MapPartitionsRDD[U, T](this, (context, pid, iter) => iter.map(cleanF))
}

distinct的情况下,fmap的参数是匿名函数x => (x, null)

这是一个在 Scala REPL 中使用匿名函数 (lambda) 的简单示例(在 Scala 列表中使用类似的 map 函数,而不是 Spark RDD):

scala> List(1,2,3).map(x => x + 1)
res0: List[Int] = List(2, 3, 4)

【讨论】:

    【解决方案2】:

    映射函数map(x => (x, null))map defined by the class

    我不明白您关于省略输入的问题。你不能在 scala 中调用一个需要一个参数而不给它参数的函数。

    【讨论】:

      猜你喜欢
      • 2020-05-23
      • 2017-10-21
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多