Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 11th, 2012  |  syntax: None  |  size: 1.65 KB  |  hits: 7  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Type-safe rectangular multidimensional array type
  2. // Function that takes a rectangular array
  3. def processArray(arr : RectArray2D[Int]) = {
  4.     // do something that assumes all rows of RectArray are the same length
  5. }
  6.  
  7. // Calling the function (OK)
  8. println(processArray(RectArray2D(
  9.     ( 0,  1,  2,  3),
  10.     (10, 11, 12, 13),
  11.     (20, 21, 22, 23)
  12. )))
  13. // Compile-time error
  14. println(processArray(RectArray2D(
  15.     ( 0,  1,  2,  3),
  16.     (10, 11, 12),
  17.     (20, 21, 22, 23, 24)
  18. )))
  19.        
  20. import shapeless._
  21.  
  22. def foo[A, N <: Nat](rect: Seq[Sized[Seq[A], N]]) = rect
  23.  
  24. val a = Seq(Sized(1, 2, 3), Sized(4, 5, 6))
  25. val b = Seq(Sized(1, 2, 3), Sized(4, 5))
  26.        
  27. case class RectArray2D[A, N <: Nat](rows: Sized[Seq[A], N]*)
  28.  
  29. def processArray(arr: RectArray2D[Int, _]) = {
  30.   // Run-time confirmation of what we've verified at compile-time.
  31.   require(arr.rows.map(_.size).distinct.size == 1)
  32.   // Do something.
  33. }
  34.  
  35. // Compiles and runs.
  36. processArray(RectArray2D(
  37.   Sized( 0,  1,  2,  3),
  38.   Sized(10, 11, 12, 13),
  39.   Sized(20, 21, 22, 23)
  40. ))
  41.  
  42. // Doesn't compile.
  43. processArray(RectArray2D(
  44.   Sized( 0,  1,  2,  3),
  45.   Sized(10, 11, 12),
  46.   Sized(20, 21, 22, 23)
  47. ))
  48.        
  49. final class Matrix[T]( cols: Int, rows: Int ) {
  50.   private val container: Array[Array[T]] = Array.ofDim[T]( cols, rows )
  51.   def get( col: Int, row: Int ) = container(col)(row)
  52.   def set( col: Int, row: Int )( value: T ) { container(col)(row) = value }
  53. }
  54.        
  55. class Rect[T] private (val data: Seq[T])
  56.  
  57. object Rect {
  58.     def apply[T](a1: (T, T), a2: (T, T)) = new Rect(Seq(a1, a2))
  59.     def apply[T](a1: (T, T, T), a2: (T, T, T), a3: (T, T, T)) = new Rect(Seq(a1, a2, a3))
  60.     // Continued...
  61. }
  62.  
  63. Rect(
  64.      (1, 2, 3),
  65.      (3, 4, 5),
  66.      (5, 6, 7))