I'm learning Haskell and currently trying to rewrite this code:
case class Coord(x: Int, y: Int)
def buildBoard(coords: [Coord]): String = {
var str = ""
for (i <- 0 to 30) {
for (j <- 0 to 40) {
if (coords.exists(c => c.x == i && c.y == j))
str += "x "
else
str += "o "
}
str += "\n"
}
str
}
This builds a simple board for a command line game that i'm writing. What's the simplest way that I can rewrite this? I'm not looking for anything performatic
I'm using tuples to implement Coord type:
type Coordinate = (Int, Int)
type Coordinates = [Coordinate]
Possible answer
I'm very grateful to those who helped. I managed to get the job done using list-comprehensions. My thought was to get rid of the "iteractive approach" of the previous code. In fact, I wanted to translate a "virtual" set of coordinates into a string, and here is how I did it:
createBoard :: Coordinates -> String
createBoard coordinates = concatMap parse board
where
parse coordinate@(_, y)
| coordinate `elem` coordinates = "x "
| y == 41 = "\n"
| otherwise = "o "
board = [ (x, y) | x <- [0..30], y <- [0..41] ]