Skip to content

Instantly share code, notes, and snippets.

@chexxor
Last active February 17, 2016 01:25
Show Gist options
  • Save chexxor/b3535e5e91ea1b63886c to your computer and use it in GitHub Desktop.
Save chexxor/b3535e5e91ea1b63886c to your computer and use it in GitHub Desktop.
Basic Example of Rock-Paper-Scissors in PureScript
module Main where
import Prelude
import Control.Monad.Eff.Console (log)
-- Define the types of data used by the game.
-- `Rock`, a data type, is better than `"Rock"`, a String,
-- because the compiler can help us. The number of possible
-- values of a String is huuuuuge, but the number of possible
-- values of a RpsChoice is only three. Well-defined choices
-- makes it easy for programmers to keep track of and
-- makes it easy for compiler to check for errors.
data RpsChoice = Rock | Paper | Scissors
data GameResult = Win | Lose
-- The game implementation. Takes two choices and returns
-- `true` if the first choice beats the second choice.
rpsWinner :: RpsChoice -> RpsChoice -> GameResult
rpsWinner Rock Scissors = Win
rpsWinner Paper Rock = Win
rpsWinner Scissors Paper = Win
rpsWinner _ _ = Lose
-- Convert the GameResult value to a human-readable value.
showGameResult :: GameResult -> String
showGameResult Win = "Win!"
showGameResult Lose = "Lose!"
-- Run the program, `rpsWinner`, with a pair of game choices.
-- Read from right-to-left.
-- The dollar-sign says "evaluate stuff to the right first,
-- then pass to the left function". Same as parentheses to
-- group operations, shown below.
main = log (showGameResult $ rpsWinner Rock Scissors)
--main = log (showGameResult (rpsWinner Rock Scissors))
-- An alternative to `showGameResult` to print the game result:
-- Use the `Show` type-class to convert `GameResult` typed value
-- to a human-readable value - "Win!" or "Lose!"
-- A "type-class" is like a statement that `x` behaves like `y`,
-- and here is how. Here, `GameResult` is `Show`able, because
-- this is how to implement the `show` function.
{-
instance showGameResult :: Show GameResult where
show Win = "Win!"
show Lose = "Lose!"
main = log (show $ rpsWinner Rock Paper)
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment