如何在scala中创建列表长度方法?
我需要创建返回列表长度的函数(当然没有standart scala方法)如何在scala中创建列表长度方法?,scala,Scala,我需要创建返回列表长度的函数(当然没有standart scala方法) val a=3::4::7::9::Nil var b=0 变量i=0 def listLength[A](xs:List[A]):Int={ 如果(xs(i)!=null&&i
val a=3::4::7::9::Nil
var b=0
变量i=0
def listLength[A](xs:List[A]):Int={
如果(xs(i)!=null&&i
对于此方法,我有一个错误:java.lang.IndexOutOfBoundsException:4您不能
列出。应用(notExisingIndex)
作为应用
您不能
List.apply(notExisingIndex)
作为apply
这xs(i)!=null不符合您的想法。List
可能包含一个null
元素,但它与List的结尾无关,因此仍然应该对其进行计数
而这个i
完全违背了在不使用.length
的情况下计算列表的长度的目的
这个(或类似的东西)可能就是你想要的
def listLength[A](xs: List[A]): Int = xs match {
case Nil => 0
case _ :: tail => 1 + listLength(tail)
}
这xs(i)!=null不符合您的想法。List
可能包含一个null
元素,但它与List的结尾无关,因此仍然应该对其进行计数
而这个i
完全违背了在不使用.length
的情况下计算列表的长度的目的
这个(或类似的东西)可能就是你想要的
def listLength[A](xs: List[A]): Int = xs match {
case Nil => 0
case _ :: tail => 1 + listLength(tail)
}
我将结合前面的两个答案得出以下结论:
def length[T](list: List[T]) = {
@tailrec
def loop(list: List[T], res: Int): Int = list match {
case Nil => res
case head :: tail => loop(tail, res+1)
}
loop(list, 0)
}
这是尾部递归,因此它编译成一个简单的循环,但它的外部函数签名中没有虚假的额外值。我将结合前面的两个答案得出以下结论:
def length[T](list: List[T]) = {
@tailrec
def loop(list: List[T], res: Int): Int = list match {
case Nil => res
case head :: tail => loop(tail, res+1)
}
loop(list, 0)
}
这是尾部递归的,因此它编译成一个简单的循环,但它在外部函数签名中没有虚假的额外值。“当然没有standart scala方法”您在i
中使用它。我的意思是,我不能使用方法length替换函数。我需要做的是)为什么要再次使用var b
。只有var i
可以在函数的末尾返回listLength[A](xs:List[A])
“当然没有standart scala方法”您在i
中使用它。我的意思是,我不能使用方法length替换函数。我需要做的是)为什么要再次使用var b
。只需在函数listLength[A](xs:List[A])的末尾返回var i
,
很乐意提供帮助。继续努力,乐意帮忙。重复fping@ArnonRotem-加洛兹,你走错方向了!这个答案不是尾部递归的,因为最后一个操作是+
而不是递归调用。公认的答案(和我的答案)是错误的。@Arnnrotem Gal Oz你的答案是错误的!这个答案不是尾部递归的,因为最后一个操作是+
而不是递归调用。被接受的答案(和我的答案)是尾部递归的。
def length[T](list: List[T]) = {
@tailrec
def loop(list: List[T], res: Int): Int = list match {
case Nil => res
case head :: tail => loop(tail, res+1)
}
loop(list, 0)
}