Deep-reverse of nested lists in Scala

前端 未结 2 601
清酒与你
清酒与你 2020-12-10 04:02

I\'d like to reverse a list of lists, recursively, in Scala.

I\'ve written deep list reverses in Python like this:

def deepReverse(items):
    if typ         


        
2条回答
  •  感动是毒
    2020-12-10 04:09

    If you wanna have this really typesafe then the typeclass pattern is your friend:

    object Reverse extends App {
    
      trait Reverser[C] {
        def reverse(xs: C): C
      }
    
      implicit def List1Reverser[A] = new Reverser[List[A]] {
        def reverse(xs: List[A]) =
          xs.reverse
      }
    
      implicit def List2Reverser[A] = new Reverser[List[List[A]]] {
        def reverse(xs: List[List[A]]) =
          xs.map(_.reverse).reverse
      }
    
      implicit def List3Reverser[A] = new Reverser[List[List[List[A]]]] {
        def reverse(xs: List[List[List[A]]]) =
          xs.map(_.map(_.reverse).reverse).reverse
      }
    
      def deepReverse[A](xs: A)(implicit rev: Reverser[A]): A =
        rev.reverse(xs)
    
      val xs = List(1,2)
      val xxs = List(List(1,2),List(1,2),List(1,2))
      val xxxs = List(List(List(1,2),List(1,2)),List(List(1,2),List(1,2)),List(List(1,2),List(1,2)))
    
      println(deepReverse(xs))
      println(deepReverse(xxs))
      println(deepReverse(xxxs))
    }
    

    The only problem with this is that you need a typeclass for each nested list type.

提交回复
热议问题