Chess Logic
| Chess.hs | |
|---|---|
- A sum type.
- A product type.
- Module should have same name as file.
- Automatically derive Eq and Show typeclasses
Enumallows for writing e.g.[A .. H]- Alternative approaches include
- Another syntax for custom datatypes, know as GADT
- A list comprehension, as in Python.
intois from the witch package, for type coercions.@Textindicates the type to coerce to.- No need to write type signatures (although it's good practice) - Haskell will infer them for you.
\caserequires theLambdaCaseextension which has been globally enabled in the project's.cabalfile.- If
Black, return function to uppercase the character. - If
White, don't change the letter case.idcan be useful. newtypeis like thedatakeyword. See more aboutnewtypehere- Alternative approaches to the
Boardtype 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.