我觉得Scala社区对编写"简洁","酷","scala惯用","单行" - 如果可能的代码有一点点的痴迷.接下来是对Java /命令/丑陋代码的比较.
虽然这(有时)导致易于理解的代码,但它也导致99%的开发人员的代码效率低下.这就是Java/C++不容易被击败的地方.
考虑这个简单的问题:给定一个整数列表,删除最大的元素.订购不需要保留.
这是我的解决方案版本(它可能不是最好的,但它是普通的非摇滚明星开发者会做的).
def removeMaxCool(xs: List[Int]) = {
val maxIndex = xs.indexOf(xs.max);
xs.take(maxIndex) ::: xs.drop(maxIndex+1)
}
Run Code Online (Sandbox Code Playgroud)
这是Scala惯用,简洁,并使用一些很好的列表功能.这也是非常低效的.它遍历列表至少3或4次.
这是我完全不那么类似Java的解决方案.这也是一个合理的Java开发人员(或Scala新手)会写的.
def removeMaxFast(xs: List[Int]) = {
var res = ArrayBuffer[Int]()
var max = xs.head
var first = true;
for (x <- xs) {
if (first) {
first = false;
} else {
if (x > max) {
res.append(max)
max = x
} else {
res.append(x)
}
}
}
res.toList
}
Run Code Online (Sandbox Code Playgroud)
完全非Scala惯用,非功能性,非简洁,但它非常有效.它只遍历列表一次!
因此,如果99%的Java开发人员编写的代码比99%的Scala开发人员更有效,那么这对于更好的Scala采用来说是一个巨大的障碍.有没有办法摆脱这个陷阱?
我正在寻找实用的建议,以避免这种"效率低下的陷阱",同时保持实施清晰简洁.
澄清:这个问题来自现实生活场景:我必须编写一个复杂的算法.首先我在Scala中编写它,然后我"必须"用Java重写它.Java实现的时间是原来的两倍,并不是很清楚,但同时它的速度是原来的两倍.重写Scala代码以提高效率可能需要一些时间并且对scala内部效率有更深入的理解(对于映射与折叠等)
我有一个列表,可能包含比较相等的元素.我想要一个类似的列表,但删除了一个元素.所以从(:a:b:c:b:d)我希望能够"删除" 一个:b得到(:a:c:b:d).
上下文是纸牌游戏中的一手牌,其中有两副标准牌正在进行中,因此可能存在重复的牌但仍然一次玩一张.
我有工作代码,见下文.在Clojure中有更多惯用的方法吗?
(defn remove-one [c left right]
(if (= right ())
left
(if (= c (first right))
(concat (reverse left) (rest right))
(remove-one c (cons (first right) left) (rest right)))))
(defn remove-card [c cards]
(remove-one c () cards))
Run Code Online (Sandbox Code Playgroud)
以下是我不久前得到的Scala答案:什么是惯用的Scala方法从一个不可变的List中"删除"一个元素?
从Scala中的列表中删除第一个对象的最佳方法是什么?
来自Java,我习惯于使用一种List.remove(Object o)
方法从列表中删除第一次出现的元素.既然我在Scala中工作,我希望该方法返回一个新的不可变List
而不是改变一个给定的列表.我也可能期望该remove()
方法采用谓词而不是对象.总之,我希望找到这样的方法:
/**
* Removes the first element of the given list that matches the given
* predicate, if any. To remove a specific object <code>x</code> from
* the list, use <code>(_ == x)</code> as the predicate.
*
* @param toRemove
* a predicate indicating which element to remove
* @return a new list with the selected object removed, or the same
* list if no objects satisfy the given predicate
*/
def …
Run Code Online (Sandbox Code Playgroud) 根据"Scala编程"一书的第44页,存在数据结构的remove
功能list
.但是,当我在我的翻译中尝试这个例子时,我不断收到错误.有谁知道为什么?这是一个例子
scala> val x = List(1,2,3,4,5,6,7,8,9)
x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> x.remove(_ < 5)
<console>:9: error: value remove is not a member of List[Int]
x.remove(_ < 5)
^
scala> x.remove(s => s == 5)
<console>:9: error: value remove is not a member of List[Int]
x.remove(s => s == 5)
^
scala> val y = List("apple","Oranges","pine","sol")
y: List[String] = List(apple, Oranges, pine, sol)
scala> y.remove(s => s.length ==4)
<console>:9: …
Run Code Online (Sandbox Code Playgroud)