Listのlengthその2

もういっちょ

#ruby
def length(arr)
  def length_loop(arr,count=0)
    if arr.empty? then count
    else
      arr.shift
      length_loop(arr,count+1)
    end
  end
  length_loop(arr)
end
puts length [1,2,3,"a"] #=>4
//Scala
def length[T](lst: List[T]):Int ={
  def lengthLoop[T](lst: List[T],count: Int):Int= lst match {
    case List() => count                             
    case List(_*) => lengthLoop(lst.tail,count+1)
    }
  lengthLoop(lst,0)
}
println(length(List(1,2,3,"a"))) //=>4

Scalaのシンタックスハイライトきぼんぬ><

//Scalaパターンマッチ時リスト分解版
def length[T](lst: List[T]):Int ={
  def lengthLoop[T](lst: List[T],count: Int):Int= lst match {
    case List() => count                             
    case head::tail => lengthLoop(tail,count+1)
    }
  lengthLoop(lst,0)
}
println(length(List(1,2,3,"a"))) //=>4