Practice Time: Lambdas
Practice Time
In this practice, you are going to write the the first part of a higher-order functions game. You will implement everything, except the higher-order functions. Let’s get started.
- Create a new file.
- Create an enum class,
Directions
, that has the directionsNORTH
,SOUTH
,EAST
andWEST
, as well asSTART
, andEND
. - Create a class
Game
. - Inside
Game
, declare a var,path
, that is a mutable list ofDirection
. Initialize it with one element,START
. - Create 4 lambdas,
north
,south
,east
, andwest
, that add the respective direction to the path. - Add another lambda,
end
, that:- Adds
END
to path - Prints “Game Over”
- Prints the path
- Clears the path
- Returns
false
- Adds
- Create a main function.
- Inside
main()
, create an instance ofGame
. - To test your code so far, in
main()
print the path, then invoke north, east, south, west, and end. Finally, print the path again.
You should see this output:
> [START] Game Over: [START, NORTH, SOUTH, EAST, WEST, END] []
// File: Main.kt
// Programmer: Engineer Nolverto Urias Obeso
// Creation Date: 06/24/2023
// Email: nolvertou@gmail.com
// Description: Practice Time of lambdas
// TODO 1: Create a new file
// TODO 2: Create an enum class, Directions, that has the directions NORTH, SOUTH, EAST and WEST,
// as well as START, and END.
enum class Direction{NORTH, SOUTH, EAST, WEST, START, END}
// TODO 3: Create a class Game.
class Game(){
var path: MutableList<Direction> = mutableListOf(Direction.START)
// TODO 5: Create 4 lambdas, north, south, east, and west,
// that add the respective direction to the path.
val addNorth = {path.add(Direction.NORTH)}
val addSouth = {path.add(Direction.SOUTH)}
val addEast = {path.add(Direction.EAST)}
val addWest = {path.add(Direction.WEST)}
// TODO 6: Add another lambda, end, that:
// Adds END to path
// Prints “Game Over”
// Prints the path
// Clears the path
// Returns false
val end:() -> (Boolean) = { ->
path.add(Direction.END) // Adds END to path
println("Game Over") // Prints “Game Over”
println("path: $path") // Prints the path
for(item in path.indices) path.removeAt(0) // Clears the path
println("path is cleaned: $path") // Prints the path after clean it
false // Returns false
}
}
// TODO 7: Create a main function.
fun main() {
// TODO 8: Inside main(), create an instance of Game.
val game = Game()
// TODO 9: To test your code so far, in main() print the path, then invoke
// north, east, south, west, and end. Finally, print the path again.
println(game.path)
game.addNorth()
game.addEast()
game.addSouth()
game.addWest()
println(game.end()) // It verifies if the return is false
}
Output:
[START]
Game Over
path: [START, NORTH, EAST, SOUTH, WEST, END]
path is cleaned: []
false
Comments
Post a Comment