1 2 3 | case class Pos(x:Int, y: Int) type Terrain = Pos => Boolean |
Essentially Terrain is a function which takes a position and for that position returns a boolean based on whether the position is accessible or not!
Given this definition of Terrain, a way to define an "infinite" terrain where every position is accessible is done this way:
1 | val infiniteTerrain = (pos: Pos) => true |
or another terrain, where certain coordinates are accessible can be defined this way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | def terrainFunction(vector: Vector[Vector[Char]]) : Terrain = { (pos: Pos) => { if (pos.x > vector.size - 1 || pos.y > vector( 0 ).size - 1 || pos.x < 0 || pos.y < 0 ) { false } else { val ch = vector(pos.x)(pos.y) ch == 'o' ; } } } val terrain1 = terrainFunction(Vector( Vector( '-' , '-' , '-' ), Vector( '-' , 'o' , '-' ), Vector( '-' , 'o' , '-' ), Vector( '-' , 'o' , '-' ), Vector( '-' , '-' , '-' ) ) ) |
All extremely clever.
Now, given that Java 8 release is imminent, an equally(almost :-) ) clever code can be attempted using Java 8 constructs:
whereas the Terrain could be defined as a function signature in Scala, it has to be defined as a functional interface with Java 8:
1 2 3 | interface Terrain { public boolean isAccessible(Pos pos); } |
Given this interface, an infinite terrain looks like this using Lambdas in Java 8:
1 | Terrain infiniteTerrain = (pos) -> true ; |
The terrainFunction equivalent in Java 8 can be defined along these lines:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public Terrain terrainFunction( char [][] arr) { return (pos) -> { if (pos.x > arr.length - 1 || pos.y > arr[ 0 ].length - 1 || pos.x < 0 || pos.y < 0 ) { return false ; } else { char ch = arr[pos.x][pos.y]; return ch == 'o' ; } }; } char [][] arr = { { '-' , '-' , '-' }, { '-' , 'o' , '-' }, { '-' , 'o' , '-' }, { '-' , 'o' , '-' }, { '-' , '-' , '-' } }; Terrain terrain = terrainFunction(arr); assertTrue(terrain.isAccessible( new Pos( 1 , 1 ))); |
Close enough!
No comments:
Post a Comment