gpt4 book ai didi

list - Scala:过滤器在 Iterator 与 List 上的行为

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

$ scala
Welcome to Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_79).
Type in expressions to have them evaluated.
Type :help for more information.

scala> Iterator(2,4,6)
res0: Iterator[Int] = non-empty iterator

scala> res0.filter
filter filterNot

scala> res0.filter
def filter(p: A => Boolean): Iterator[A]

//给定过滤器的这个定义,我希望下面的表达式 (1) 起作用:

scala> Iterator(2,4,6).filter(Set(1,2,3).contains).toSet
res1: scala.collection.immutable.Set[Int] = Set(2)

//问题 #1: 下面的表达式 (2) 是如何工作的?它从哪里得到 A => Boolean 推断?我想问, bool 值从哪里来?

scala> Iterator(2,4,6).filter(Set(1,2,3)).toSet
res2: scala.collection.immutable.Set[Int] = Set(2)

//问题 #2:表达式 (1) 与 (2) 哪个更好,为什么?

//在 List 上尝试了同样的事情,我希望它能工作。

 scala> List(2,4,6).filter(List(1,2,3).contains)
res3: List[Int] = List(2)

//问题 #3:为什么这对 Iterator 神奇地有效却不起作用?

scala>  List(2,4,6).filter(List(1,2,3))
<console>:8: error: type mismatch;
found : Int(1)
required: Boolean
List(2,4,6).filter(List(1,2,3))

最佳答案

Question # 1: How does the below expression (2) work ? Where does it get the A => Boolean inference from ? I meant to ask, where's the Boolean coming from ?

Set[A] extends (A) => Boolean,所以 Set(1, 2, 3) 一个函数 A => bool 值。我们可以很容易地看到,因为它有一个 apply 方法来测试元素是否包含在 Set 中。

scala> Set(1, 2, 3)(2)
res22: Boolean = true

Question # 2: Which one is better expression (1) vs (2) and why ? Tried the same thing on List and I expected this to work.

哪个更好是一个见仁见智的问题——它们在功能上是完全一样的。对于那些熟悉 Set 的人来说,应该清楚它们的作用(它们都等同于 contains)。有人可能说使用 Set(1, 2, 3).contains 可以更清楚地说明它的作用。 List 有一个 apply 方法,但与 Set 不同。 List#applyInt => A -- 一种通过索引从 List 中检索元素的方法。所以对于列表,你必须使用contains

Question # 3: Why doesn't this work when it magically worked for Iterator ?

这实际上与#2 相同。 List(1, 2, 3).apply 不是 Int => Boolean,它是 Int => Int

关于list - Scala:过滤器在 Iterator 与 List 上的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30265090/

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