如果找不到元素,为什么 Scala 的索引方法返回 -1 而不是 None ? [英] Why do Scala's index methods return -1 instead of None if the element is not found?

查看:47
本文介绍了如果找不到元素,为什么 Scala 的索引方法返回 -1 而不是 None ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道为什么在 Scala 中使用各种索引方法来确定集合中元素的位置(例如 List.indexOfList.indexWhere)返回 -1 表示集合中不存在给定元素,而不是更惯用的 Option[Int].返回 -1 而不是 None 有什么特别的好处,还是只是因为历史原因?

I've always been wondering why in Scala the various index methods for determining the position of an element in a collection (e.g. List.indexOf, List.indexWhere) return -1 to indicate the absence of the given element in the collection, instead of a more idiomatic Option[Int]. Is there some particular advantage to returning -1 instead of None, or is this just for historical reasons?

推荐答案

这只是历史原因,但后来人们想知道历史原因是什么:历史是什么,为什么会变成这样?

It is just for historical reasons, but then one wants to know what the historical reasons are: what was the history, and why did it turn out that way?

直接历史记录是 java.lang.String.indexOf 方法,它返回索引,如果没有找到匹配的字符,则返回 -1.但这并不是什么新鲜事.如果在字符串中找不到任何字符,Fortran SCAN 函数将返回 0,这与 Fortran 使用 1 索引的情况相同.

The immediate history is the java.lang.String.indexOf method, which returns the index, or -1 if no matching character is found. But this is hardly new; the Fortran SCAN function returns 0 if no character is found in a string, which is the same thing given that Fortran uses 1-indexing.

这样做的原因是字符串只有正长度,因此任何负长度都可以用作 None 值,而无需任何装箱开销.-1 是最方便的负数,仅此而已.

The reason to do this is that strings have only positive length, so any negative length can be used as a None value without any overhead of boxing. -1 is the most convenient negative number, so that's it.

如果编译器不够聪明,无法意识到所有装箱和拆箱以及一切都无关紧要,那么这会加起来.特别是,一个对象创建往往需要 5-10 ns,而函数调用或比较通常需要 1-2 ns,所以如果集合很短,创建一个新对象可能会有相当大的分数损失(如果你的内存已经被占用了,GC 有很多工作要做).

And this can add up if the compiler isn't smart enough to realize that all the boxing and unboxing and everything is irrelevant. In particular, an object creation tends to take 5-10 ns, while a function call or comparison typically takes more like 1-2 ns, so if the collection is short, creating a new object can have a sizable fractional penalty (more so if your memory is already taxed and the GC has a lot of work to do).

如果 Scala 最初有一个了不起的优化器,那么选择可能会有所不同,因为人们只需编写带有选项的东西,这样更安全且不那么特殊,然后信任编译器将其转换为适当的高性能代码.

If Scala had initially had an amazing optimizer, then the choice probably would have been different, as one would just write things with options, which is safer and less of a special case, and then trust the compiler to convert it into appropriately high-performance code.

这篇关于如果找不到元素,为什么 Scala 的索引方法返回 -1 而不是 None ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆