Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added a version of the turtle example from Seth Tisue's talk on lenses.
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -0,0 +1,65 @@ | |||
{-# LANGUAGE TemplateHaskell #-} | |||
{-# LANGUAGE DeriveDataTypeable #-} | |||
-- | A simple Turtle-graphics demonstration for modeling the location of a turtle. | |||
-- | |||
-- This is based on the code presented by Seth Tisue at the Boston Area Scala | |||
-- Enthusiasts meeting during his lens talk. | |||
-- | |||
-- Usage: | |||
-- | |||
-- > def & forward 10 & down & color .~ red % turn (pi/2) & forward 5 | |||
module Turtle where | |||
|
|||
import Control.Lens hiding (up, down) | |||
import Data.Default | |||
|
|||
data Point = Point | |||
{ _x, _y :: Double | |||
} deriving (Eq,Show) | |||
|
|||
makeClassy ''Point | |||
|
|||
instance Default Point where | |||
def = Point def def | |||
|
|||
data Color = Color | |||
{ _r, _g, _b :: Int | |||
} deriving (Eq,Show) | |||
|
|||
makeClassy ''Color | |||
|
|||
red :: Color | |||
red = Color 255 0 0 | |||
|
|||
instance Default Color where | |||
def = Color def def def | |||
|
|||
data Turtle = Turtle | |||
{ _tPoint :: Point | |||
, _tColor :: Color | |||
, _heading :: Double | |||
, _penDown :: Bool | |||
} deriving (Eq,Show) | |||
|
|||
makeClassy ''Turtle | |||
|
|||
instance Default Turtle where | |||
def = Turtle def def def False | |||
|
|||
instance HasPoint Turtle where | |||
point = tPoint | |||
|
|||
instance HasColor Turtle where | |||
color = tColor | |||
|
|||
forward :: Double -> Turtle -> Turtle | |||
forward d t = | |||
t & y +~ d * cos (t^.heading) | |||
& x +~ d * sin (t^.heading) | |||
|
|||
turn :: Double -> Turtle -> Turtle | |||
turn d = heading +~ d | |||
|
|||
up, down :: Turtle -> Turtle | |||
up = penDown .~ False | |||
down = penDown .~ True |