[Haskell-beginners] Dipping Toes Into Haskell
Mike Meyer
mwm at mired.org
Fri Mar 13 00:03:51 UTC 2015
On Thu, Mar 12, 2015 at 6:02 PM, Timothy Washington <twashing at gmail.com>
wrote:
> To get started, I'm trying to implement a simple *tictactoe* game. And I
> would like to be able to represent a Piece on the board, as either the
> string "X" or "O". This is what I have so far.
>
> module Main where
>
> data Piece = X | O
> type Row = [Piece]
> type Board = [Row]
>
> -- put an X or O in a position
> move :: Board -> Piece -> Board
> move board piece = board
>
> -- check win vertically
> -- check win horizontally
> -- check win diagonally
>
> main :: IO ()
> main = putStrLn "Hello World"
>
>
>
> *A)* Now, I'd like to be able to *load code interactively*, preferably
> within emacs. However I don't have access to my types with *ghci* or *ghc-mod
> (Interactive-Haskell)*. In either case, this call fails with the below
> error.
>
>
> let p = Piece X
> <interactive>:20:9-13: Not in scope: data constructor `Piece'
>
>
Piece is the data TYPE. It has two constructors, X, and O. If you load your
module into ghci, you can do ":t X" to get the type of X, which is Piece.
You want to do "let p = X" here.
Check your mode docs while editing the haskell file. There should be a
command to load the current buffer into a ghci running in an interactive
emacs buffer.
> *B)* And how do I make a *custom datatype* that's one of two strings
> (enumeration of either "X" or "O"). Cabal builds and runs the abouve code,
> so I know it can compile. But I'm confused as to where X or O is defined,
> and how I would supply it as an input.
>
As noted, you can derive "Show" so that Piece types print as "X" and "O".
Similarly, you can derive "Read":
data Piece = X | O deriving (Show, Read)
so that you can then read "X" and get back an X when the context calls for
a Piece value:
*Main> read "X" :: Piece
X
However, this isn't used a lot, as it tends to be slow and not very
flexible for more complex types. For instance, it will let you read in
lists of Pieces and lists of lists, but you'l lhave to use the list syntax,
not something that looks like an actual board when printed.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150312/6e56f34c/attachment-0001.html>
More information about the Beginners
mailing list