Chess Logic
- A sum type.
- A product type.
- Module should have same name as file.
- Automatically derive Eq and Show typeclasses
Enum
allows for writing e.g.[A .. H]
- Alternative approaches include
- Another syntax for custom datatypes, know as GADT
- A list comprehension, as in Python.
into
is from the witch package, for type coercions.@Text
indicates the type to coerce to.- No need to write type signatures (although it's good practice) - Haskell will infer them for you.
\case
requires theLambdaCase
extension which has been globally enabled in the project's.cabal
file.- If
Black
, return function to uppercase the character. - If
White
, don't change the letter case.id
can be useful. newtype
is like thedata
keyword. See more aboutnewtype
here- Alternative approaches to the
Board
type include.
Analysis¶
Because custom types are so easily made and expressive, it is typical in Haskell to create types that model your problem domain (here various chess-related types).
The central type is Board
, which represents the state of a chessboard. We have chosen to directly represent the board's state as a function from a square (specified by file and rank) to the square's state.
A good example of type-based refactoring in Haskell is to change Board
to an alternative representation and then fix the series of type errors that Haskell will show you in order to make the new Board
type work across your project.
Alternative approaches¶
initBoard
¶
Tip
To understand how this works, lookup the types of const
and curry
on Hoogle (both are common and useful functions).
Then ascertain the type of const Empty
with VSCode, namely:
(const Empty) :: (File, Rank) -> SquareState
Convince yourself that this is an appropriate input type for curry
, and an appropriate output type for const
.
Board
¶
Created: August 18, 2022