Skip to content

Instantly share code, notes, and snippets.

@kaja47
Created July 31, 2012 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaja47/3218725 to your computer and use it in GitHub Desktop.
Save kaja47/3218725 to your computer and use it in GitHub Desktop.
// Scala version of this http://haskelllive.com/
val initialBoardStr = Seq(
"rnbqkbnr",
"pppppppp",
" ",
" ",
" ",
" ",
"PPPPPPPP",
"RNBQKBNR"
) mkString "\n"
def showBoard(b: Board): String = b map (_ map showSquare mkString) mkString "\n"
def readBoard(b: String): Board = b split "\n" map (_ map readSquare)
type Square = Option[Piece]
def showSquare(s: Square): Char = s map showPiece getOrElse ' '
def readSquare(s: Char): Square = s match {
case ' ' => None
case s => Some(readPiece(s))
}
type Piece = (Color, Type)
def showPiece(p: Piece): Char = p match {
case (White, t) => showType(t) toUpper
case (Black, t) => showType(t)
}
def showType(t: Type): Char = t match {
case Pawn => 'p'
case Knight => 'n'
case Bishop => 'b'
case Rook => 'r'
case King => 'k'
case Queen => 'q'
}
def readPiece(p: Char): Piece = p match {
case p if p isUpper => (White, readType(p))
case p => (Black, readType(p))
}
def readType(t: Char): Type = t toLower match {
case 'p' => Pawn
case 'n' => Knight
case 'b' => Bishop
case 'r' => Rook
case 'k' => King
case 'q' => Queen
}
sealed trait Color
case object White extends Color
case object Black extends Color
sealed trait Type
case object Pawn extends Type
case object Knight extends Type
case object Bishop extends Type
case object Rook extends Type
case object King extends Type
case object Queen extends Type
println(showBoard(readBoard(initialBoardStr)) == initialBoardStr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment