scala 有没有比这个更好的方法在列表中做正方形?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17686969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a better way to do square in a list rather than this?
提问by Lengoman
I am trying to simplify a square call.
我正在尝试简化方形调用。
Is this the best way?
这是最好的方法吗?
(1 to 10).map(x => x*x)
回答by axel22
Declare this once somewhere:
在某处声明一次:
def sqr(x: Int) = x * x
And use it like this afterwards:
然后像这样使用它:
(1 to 10).map(sqr)
回答by Nikita Volkov
Since squaring is exponentiation to the power 2, it makes sense to consider the following two approaches:
由于平方是 2 次幂的幂,因此考虑以下两种方法是有意义的:
scala> (1 to 10).map(math.pow(_, 2))
res6: scala.collection.immutable.IndexedSeq[Double] = Vector(1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0, 100.0)
scala> (1 to 10).map(BigInt(_).pow(2))
res7: scala.collection.immutable.IndexedSeq[scala.math.BigInt] = Vector(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
回答by Matthew Saltz
This is possibly a bit overkill, but it's reasonably simple and kind of cool:
这可能有点矫枉过正,但它相当简单而且很酷:
object SquareApp extends App {
implicit class SquareableInt(i: Int) extends AnyVal { def squared = i*i }
(0 until 10).map(_ squared)
}
The implicitfunction automatically converts any Int on which squaredis called into a SquareableIntobject temporarily.
该implicit函数会自动将任何squared被调用的IntSquareableInt临时转换为 对象。

