获取 Scala 列表中的项目?

发布于 2024-10-17 10:13:16 字数 488 浏览 3 评论 0原文

你究竟如何从 scala 的 List 中获取索引 i 处的元素?

我尝试了 get(i)[i] - 没有任何效果。谷歌搜索仅返回如何“查找”列表中的元素。但我已经知道元素的索引了!

这是无法编译的代码:

def buildTree(data: List[Data2D]):Node ={
  if(data.length == 1){
      var point:Data2D = data[0]  //Nope - does not work
       
  }
  return null
}

查看 List api 没有帮助,因为我的眼睛只是交叉。

How in the world do you get just an element at index i from the List in scala?

I tried get(i), and [i] - nothing works. Googling only returns how to "find" an element in the list. But I already know the index of the element!

Here is the code that does not compile:

def buildTree(data: List[Data2D]):Node ={
  if(data.length == 1){
      var point:Data2D = data[0]  //Nope - does not work
       
  }
  return null
}

Looking at the List api does not help, as my eyes just cross.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

十二 2024-10-24 10:13:16

使用括号:

data(2)

但是您实际上并不想经常对列表执行此操作,因为遍历链接列表需要时间。如果要索引到集合中,请使用 Vector (不可变)或 ArrayBuffer (可变)或可能的 Array (这只是一个 Java 数组,除非您再次使用 (i) 而不是 [i] 对其进行索引)。

Use parentheses:

data(2)

But you don't really want to do that with lists very often, since linked lists take time to traverse. If you want to index into a collection, use Vector (immutable) or ArrayBuffer (mutable) or possibly Array (which is just a Java array, except again you index into it with (i) instead of [i]).

空城仅有旧梦在 2024-10-24 10:13:16

更安全的是使用 lift,这样您就可以提取该值(如果存在),如果不存在则优雅地失败。

data.lift(2)

如果列表不够长,无法提供该元素,则返回 None;如果足够,则返回 Some(value)。

scala> val l = List("a", "b", "c")
scala> l.lift(1)
Some("b")
scala> l.lift(5)
None

每当您执行可能以这种方式失败的操作时,最好使用选项并获取类型系统来帮助确保您正在处理元素不存在的情况。

解释:

这是有效的,因为List的apply(它只是括号,例如l(index))就像一个在任何地方定义的部分函数该列表有一个元素。 List.lift 方法通过基本上包装结果,将部分 apply 函数(仅为某些输入定义的函数)转换为普通函数(为任何输入定义)在一个选项中。

Safer is to use lift so you can extract the value if it exists and fail gracefully if it does not.

data.lift(2)

This will return None if the list isn't long enough to provide that element, and Some(value) if it is.

scala> val l = List("a", "b", "c")
scala> l.lift(1)
Some("b")
scala> l.lift(5)
None

Whenever you're performing an operation that may fail in this way it's great to use an Option and get the type system to help make sure you are handling the case where the element doesn't exist.

Explanation:

This works because List's apply (which sugars to just parentheses, e.g. l(index)) is like a partial function that is defined wherever the list has an element. The List.lift method turns the partial apply function (a function that is only defined for some inputs) into a normal function (defined for any input) by basically wrapping the result in an Option.

命硬 2024-10-24 10:13:16

为什么要加括号?

这是programming in scala一书中的引用。

此示例说明的另一个重要思想将让您深入了解为什么在 Scala 中使用括号访问数组。 Scala 的特殊情况比 Java 少。数组只是类的实例,就像 Scala 中的任何其他类一样。当您将一个或多个值括在括号中时,Scala 会将代码转换为对该变量调用名为 apply 的方法。因此greetStrings(i) 被转换成greetStrings.apply(i)。因此,在 Scala 中访问数组的元素只是像其他方法一样的方法调用。这一原则不仅限于数组:对象对括号中某些参数的任何应用都将转换为 apply 方法调用。当然,只有当该类型的对象实际定义了 apply 方法时,才会编译。所以这并不是一个特例;这是一般规则。

以下是如何使用函数式编程风格提取某些元素(在本例中为第一个元素)的一些示例。

  // Create a multdimension Array 
  scala> val a = Array.ofDim[String](2, 3)
  a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))
  scala> a(0) = Array("1","2","3")
  scala> a(1) = Array("4", "5", "6")
  scala> a
  Array[Array[String]] = Array(Array(1, 2, 3), Array(4, 5, 6))

  // 1. paratheses
  scala> a.map(_(0))
  Array[String] = Array(1, 4)
  // 2. apply
  scala> a.map(_.apply(0))
  Array[String] = Array(1, 4)
  // 3. function literal
  scala> a.map(a => a(0))
  Array[String] = Array(1, 4)
  // 4. lift
  scala> a.map(_.lift(0))
  Array[Option[String]] = Array(Some(1), Some(4))
  // 5. head or last 
  scala> a.map(_.head)
  Array[String] = Array(1, 4)

Why parentheses?

Here is the quote from the book programming in scala.

Another important idea illustrated by this example will give you insight into why arrays are accessed with parentheses in Scala. Scala has fewer special cases than Java. Arrays are simply instances of classes like any other class in Scala. When you apply parentheses surrounding one or more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. So greetStrings(i) gets transformed into greetStrings.apply(i). Thus accessing an element of an array in Scala is simply a method call like any other. This principle is not restricted to arrays: any application of an object to some arguments in parentheses will be transformed to an apply method call. Of course this will compile only if that type of object actually defines an apply method. So it's not a special case; it's a general rule.

Here are a few examples how to pull certain element (first elem in this case) using functional programming style.

  // Create a multdimension Array 
  scala> val a = Array.ofDim[String](2, 3)
  a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))
  scala> a(0) = Array("1","2","3")
  scala> a(1) = Array("4", "5", "6")
  scala> a
  Array[Array[String]] = Array(Array(1, 2, 3), Array(4, 5, 6))

  // 1. paratheses
  scala> a.map(_(0))
  Array[String] = Array(1, 4)
  // 2. apply
  scala> a.map(_.apply(0))
  Array[String] = Array(1, 4)
  // 3. function literal
  scala> a.map(a => a(0))
  Array[String] = Array(1, 4)
  // 4. lift
  scala> a.map(_.lift(0))
  Array[Option[String]] = Array(Some(1), Some(4))
  // 5. head or last 
  scala> a.map(_.head)
  Array[String] = Array(1, 4)
一杯敬自由 2024-10-24 10:13:16

请使用括号()访问元素列表,如下所示。

list_name(index)

Please use parentheses () to access the list of elements, as shown below.

list_name(index)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文