Scala foldLeft 方法实现自定义的 reverse 方法

1, 常规实现:

scala> val list = List(1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5)

scala> list.foldLeft(List.empty[Int])((res, cur) => cur::res)
res0: List[Int] = List(5, 4, 3, 2, 1)



2, 加上泛型:

scala> val list = List(1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5)

scala> def reverse[T](list: List[T]) =
     | list.foldLeft(List.empty[T])((res,cur) => cur::res)
reverse: [T](list: List[T])List[T]

scala> reverse(list)
res1: List[Int] = List(5, 4, 3, 2, 1)

scala> val l = List("aa","bb","tt","yy")
l: List[String] = List(aa, bb, tt, yy)

scala> reverse(l)
res2: List[String] = List(yy, tt, bb, aa)





你可能感兴趣的:(scala,reverse,foldLeft)