English 中文(简体)
复读印刷方法中的射线
原标题:Arrays in recursive print method
  • 时间:2011-11-16 13:23:43
  •  标签:
  • arrays
  • scala

I m试图使<代码>印本替换,即产出以更可读格式封存。 最好举一个例子说明这一点:如List(Set(Vector(1.0,1.1),Vctor(0d)), Set(Vector(a),“b”,“c”, Vector(x”,“y”)

List
  Set
    Vector(1.0, 1.1)
    Vector(0.0)
  Set
    Vector(a, b, c)
    Vector(x, y)

如果没有类型抹去,那将非常容易,但我已经来到这里。

def rprint(a: Any, indent: Int = 0): Unit = a match {
  case x: Traversable[_] =>
    if (x.isEmpty)
      rprint(x.toString, indent)
    else x.head match {
      case y: Traversable[_] => {
        rprint(x.toString.takeWhile(_ !=  ( ), indent)
        x foreach {i => rprint(i, indent + 2)}
      }
      case y => rprint(x.toString, indent)
    }
  case x => println(" " * indent + x)
}

我在努力争取与Arrays一道工作,而没有大量的法典重复。 我同他们一样,为其他收集工作。 具体地说:

  • 轨道不适用<代码>。

  • could convert Arrays using genericArrayOps to ArrayOps which is TraversableOnce, but TraversableOnce doesn t have a head method, so I can t see how to get an element to check its type

  • toString doesn t work quite like other collections (use .deep)

将阿雷拉纳入这一方法的最佳方式是什么,或者是否采取可以更好发挥作用的不同做法?

最佳回答

使其更灵活地界定一个海峡,其中包括实用方法和一种抽象方法,从而可以将其用作<代码>Array(1,2版>:

trait Printable[T] {
  def str(indent: Int = 0): String
  def str: String = str(0)
  def print(indent: Int = 0): Unit = println(str(indent))
  def print: Unit = print(0)
}

然后,如<条码>、和<条码>,<条码/代码>即为<条码>。 任何:

implicit def any2Printable(a: Any): Printable[Any] = new Printable[Any] {
  import collection._
  def name = a match {
    case a: Array[_] => "Array"
    case g: GenTraversableLike[_, _] => g.stringPrefix 
    case i: Iterator[_] => "Iterator"
    case _ => ""
  }
  object Iter {
    def unapply(a: Any): Option[GenIterable[_]] = a match {
      case a: Array[_] => Some(a.toIterable)
      case t: GenTraversableOnce[_] => Some(t.toIterable)
      case _ => None
    }
  }
  object Nested {
    def unapply(i: GenIterable[_]): Option[GenIterable[_]] = i match {
      case nested if i.exists{case Iter(j) =>true case _ =>false} => Some(nested)
      case _ => None
    }
  }
  def str(indent: Int = 0) = " " * indent + (a match {
    case Iter(i) if i.isEmpty => name + " <empty>"
    case Iter(Nested(i)) => name + "
" + i.map(_.str(indent+2)).mkString("
")
    case Iter(i) => name + i.map(_.toString).mkString("(", ", ", ")")
    case _ => a.toString
  })
}

这种做法处理任意的深层nes,但为了收集不包含藏书的藏书而赢得使用多种渠道,例如印刷:

Array
  Set
    Array(1.0, 1.1)
    Vector <empty>
    Array <empty>
    Set
      Vector(a, b, c)
      Vector(x, y)
      List
        Set
          Array(1.0, 1.1)
          Vector(0.0)
        Set
          Vector(a, b, c)
          Vector(x, y)
问题回答

http://www.scala-lang.org/api/scala/collection/mutable/WrappedArray.html” rel=“nofollow”>。

Try tu在对应短语中使用更一般的类型,例如GenTraversable,以形成一种默示的转换。

import scala.collection.GenTraversable

def rprint[T](a: T, indent: Int = 0): Unit = a match {
  case x: String => println(" "*indent +  "  + x +  " )
  case x: GenTraversable[_] =>
    println(" "*indent + (x.stringPrefix))
    x foreach (rprint(_, indent+2))
  case x: Array[_] =>
    println(" "*indent + (a.getClass.getSimpleName))
    x foreach (rprint(_, indent+2))
  case x => println(" "*indent + x)
}

rprint(Map(1->"one",2->"two"))
rprint(List("one", "two"))           //I don t know why this type is printed weird: $colon$colon
rprint(Array(1,2))                   //This prints less weird: int[]

你可以增加具体失踪类型(如拖车)的更多案件。

我可以说明印刷某些类型名称的问题(如<代码>List和Array——见功能定义后的例子)。 http://www.un.org/Depts/DGACM/index_chinese.htm

I ve also try to connect type Array and GenTraversable - because there is implicit conversion from Array to WrapperArray <: GenTraversable.
The solution below doesn t satisfy as it prints "WrappedArray" instead "Array", when we call the function with Array instance

case x: Array[_] => rprint(x:GenTraversable[_])

Edit:
I ve changed name extractor for GenTraversable to a.stringPrefix

It wasn t my intention to answer my own question, but I have something that works. I think it can be improved a lot, so suggestions are appreciated. There is still repetition and a rather ugly cast in there.

  def rprint(a: Any, indent: Int = 0): Unit = {
    val (typeStr, fullStr) = a match {
      case x: collection.mutable.WrappedArray[_] => ("Array", x.deep.toString)
      case x: Traversable[_] => (x.stringPrefix, x.toString)
      case _ => ("", "")
    }
    a match {
      case x: Traversable[_] =>
        if (x.isEmpty)
          rprint(typeStr + " <empty>", indent)
        else 
          x.head match {
            case _: Array[_] => {
              rprint(typeStr, indent)
              x foreach {i => rprint(genericWrapArray(
                                       i.asInstanceOf[Array[_]]), indent + 2)}
            }
            case _: Traversable[_] => {
              rprint(typeStr, indent)
              x foreach {i => rprint(i, indent + 2)}
            }
            case _ => rprint(fullStr, indent)
          }
      case x: Array[_] => rprint(genericWrapArray(x))
      case x => println(" " * indent + x)
    }
  }

测试:

scala> rprint(List(Array(Vector(1.0,1.1), Vector(0d)), Array(Array("a", "b", "c"), Array("x", "y"))))
List
  Array
    Vector(1.0, 1.1)
    Vector(0.0)
  Array
    Array(a, b, c)
    Array(x, y)




相关问题
WordPress Data Storage Efficiency

I ve been asked to review a WordPress plugin of sorts and try to find ways of making it faster. The premise of this plugin is basically to store a bunch of users and shifts and appointments and ...

Convert a 2D array index into a 1D index

I have two arrays for a chess variant I am coding in java...I have a console version so far which represents the board as a 1D array (size is 32) but I am working on making a GUI for it and I want it ...

Convert an array of integers for use in a SQL "IN" clause

Surely there is a framework method that given an array of integers, strings etc converts them into a list that can be used in a SQL "IN" clause? e.g. int[] values = {1,2,3}; would go to "(1,2,3)"

Sorting twodimensional Array in AS3

So, i have a two-dimensional Array of ID s and vote count - voteArray[i][0] = ID, voteArray[i][1] = vote count I want the top 3 voted items to be displayed in different colors, so i have a 2nd Array -...

C++ Array Sort Me

Stuck on an array sorter. Have to sort numbers from largest to smallest. I m trying two loops (one nested in the other). Here s the code: int counter=0; // inner counter int counter2=0; // outer ...

PHP array callback functions for cleaning output

I have an array of output from a database. I am wondering what the cleanest way to filter the values is example array Array ( [0] => Array ( [title] => title 1 ...

Best practice of big javascript objects

sry for this imprecise topic name. I am querying a dataset a lot of times so using ajax request would end up in tons of http requests. For this reason I decided to use the json encode method to ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

热门标签