Listのlength
再帰の勉強
#Ruby #Arrayで代用・・・ def length(arr) if arr.empty? then 0 else arr.shift 1 + length(arr) end end puts length [1,2,3,4] #=>4
ついでにScalaをちょっぴり勉強
//Scala def length(lst: List[Int]):Int = if (lst == Nil) 0 else length(lst.tail)+1 println(length(List(1,2,3,4))) //=>4 //型パラメータ def length[T](lst: List[T]):Int = if (lst == Nil) 0 else length(lst.tail)+1 println(length(List("a","b","c",1))) //=>4 //パターンマッチ使用 def length[T](lst: List[T]):Int = lst match { case List() => 0 case List(_*) => length(lst.tail)+1 } println(length(List("a","b","c",1))) //=>4