Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Type-safe rectangular multidimensional array type
- // Function that takes a rectangular array
- def processArray(arr : RectArray2D[Int]) = {
- // do something that assumes all rows of RectArray are the same length
- }
- // Calling the function (OK)
- println(processArray(RectArray2D(
- ( 0, 1, 2, 3),
- (10, 11, 12, 13),
- (20, 21, 22, 23)
- )))
- // Compile-time error
- println(processArray(RectArray2D(
- ( 0, 1, 2, 3),
- (10, 11, 12),
- (20, 21, 22, 23, 24)
- )))
- import shapeless._
- def foo[A, N <: Nat](rect: Seq[Sized[Seq[A], N]]) = rect
- val a = Seq(Sized(1, 2, 3), Sized(4, 5, 6))
- val b = Seq(Sized(1, 2, 3), Sized(4, 5))
- case class RectArray2D[A, N <: Nat](rows: Sized[Seq[A], N]*)
- def processArray(arr: RectArray2D[Int, _]) = {
- // Run-time confirmation of what we've verified at compile-time.
- require(arr.rows.map(_.size).distinct.size == 1)
- // Do something.
- }
- // Compiles and runs.
- processArray(RectArray2D(
- Sized( 0, 1, 2, 3),
- Sized(10, 11, 12, 13),
- Sized(20, 21, 22, 23)
- ))
- // Doesn't compile.
- processArray(RectArray2D(
- Sized( 0, 1, 2, 3),
- Sized(10, 11, 12),
- Sized(20, 21, 22, 23)
- ))
- final class Matrix[T]( cols: Int, rows: Int ) {
- private val container: Array[Array[T]] = Array.ofDim[T]( cols, rows )
- def get( col: Int, row: Int ) = container(col)(row)
- def set( col: Int, row: Int )( value: T ) { container(col)(row) = value }
- }
- class Rect[T] private (val data: Seq[T])
- object Rect {
- def apply[T](a1: (T, T), a2: (T, T)) = new Rect(Seq(a1, a2))
- def apply[T](a1: (T, T, T), a2: (T, T, T), a3: (T, T, T)) = new Rect(Seq(a1, a2, a3))
- // Continued...
- }
- Rect(
- (1, 2, 3),
- (3, 4, 5),
- (5, 6, 7))
Advertisement
Add Comment
Please, Sign In to add comment