Chess Logic
- 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¶
```haskell
initBoard :: Board initBoard = Board $ \f r -> Empty ```
```haskell
initBoard :: Board initBoard = Board $ _ _ -> Empty ```
```haskell
initBoard :: Board initBoard = Board $ curry $ const Empty ```
!!! Tip
To understand how this works, lookup the types of `const` and `curry` on [Hoogle](/gettingstarted/overview/#step-4-hoogle) (both are common and useful functions).
Then ascertain the type of `const Empty` with VSCode, namely:
- `#!hs (const Empty) :: (File, Rank) -> SquareState`
Convince yourself that this is an appropriate input type for `curry`, and an appropriate output type for `const`.
Board¶
```haskell
data SquareState where Empty :: SquareState HasPiece :: Piece -> SquareState
newtype Board where
Board :: (File -> Rank -> SquareState) -> Board
```
Created: August 18, 2022