获取 Scala 列表中的项目?
你究竟如何从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用括号:
但是您实际上并不想经常对列表执行此操作,因为遍历链接列表需要时间。如果要索引到集合中,请使用
Vector
(不可变)或ArrayBuffer
(可变)或可能的Array
(这只是一个 Java 数组,除非您再次使用(i)
而不是[i]
对其进行索引)。Use parentheses:
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) orArrayBuffer
(mutable) or possiblyArray
(which is just a Java array, except again you index into it with(i)
instead of[i]
).更安全的是使用
lift
,这样您就可以提取该值(如果存在),如果不存在则优雅地失败。如果列表不够长,无法提供该元素,则返回 None;如果足够,则返回 Some(value)。
每当您执行可能以这种方式失败的操作时,最好使用选项并获取类型系统来帮助确保您正在处理元素不存在的情况。
解释:
这是有效的,因为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.This will return None if the list isn't long enough to provide that element, and Some(value) if it is.
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. TheList.lift
method turns the partialapply
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.为什么要加括号?
这是programming in scala一书中的引用。
以下是如何使用函数式编程风格提取某些元素(在本例中为第一个元素)的一些示例。
Why parentheses?
Here is the quote from the book programming in scala.
Here are a few examples how to pull certain element (first elem in this case) using functional programming style.
请使用括号
()
访问元素列表,如下所示。Please use parentheses
()
to access the list of elements, as shown below.