File: Turtle.hs

package info (click to toggle)
haskell-lens 5.3.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,060 kB
  • sloc: haskell: 16,249; ansic: 20; makefile: 8
file content (65 lines) | stat: -rw-r--r-- 1,317 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
import Data.Default.Class

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