[英]What is complexity of cons operator in Scala/OCaml?
What is complexity of these codes?这些代码的复杂度是多少?
I have written the following code:我写了以下代码:
let rec replicate (element, reps) =
if reps < 0 then failwith "Negative reps"
else if reps = 0 then []
else element :: replicate (element, reps - 1);;
def replicate[A](element:A, reps:Int):List[A] =
if (reps < 0) throw new Exception("Negative reps")
else if (reps == 0) Nil
else element :: replicate(element, reps-1)
I wonder especially what is complexity of cons operator (::).我特别想知道 cons 运算符 (::) 的复杂性是什么。
Cons is O(1)
so these codes are O(n)
.缺点是O(1)
所以这些代码是O(n)
。
However this code is inefficient because it does not use tail recursion and therefore cannot be optimised into a loop (or at least using tail call elimination).但是,此代码效率低下,因为它不使用尾递归,因此无法优化为循环(或至少使用尾调用消除)。
Something like this is better (for Scala)这样的东西更好(对于 Scala)
def replicate[A](element: A, reps: Int): List[A] = {
@annotation.tailrec
def loop(rem: Int, res: List[A]): List[A] =
if (rem <= 0) {
res
} else {
loop(rem - 1, element :: res)
}
if (reps < 0) {
throw new Exception("Negative reps")
} else {
loop(reps, Nil)
}
}
This is optimised to a loop by Scala, and also avoids testing the error condition every iteration.这由 Scala 优化为一个循环,并且还避免了每次迭代都测试错误条件。
Of course in Scala it is easier just to use当然在 Scala 中使用起来更容易
List.fill(reps)(element)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.