Skip to content

Instantly share code, notes, and snippets.

@tuttlem
Created March 18, 2014 14:29
Show Gist options
  • Save tuttlem/9621183 to your computer and use it in GitHub Desktop.
Save tuttlem/9621183 to your computer and use it in GitHub Desktop.
Lens example
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens
data Ball = Ball { _position :: (Double, Double), _velocity :: (Double, Double) }
deriving (Show)
-- create the accessors for the Ball type
makeLenses ''Ball
-- | Animates a ball's position with respect to a timestep.
-- Takes a ball's existing position and velocity and animates it
-- by the time step provided
--
animate :: Ball -> Double -> Ball
animate b t = do
position .~ (px + vx * t, py + vy * t) $ b
where (px, py) = b ^. position
(vx, vy) = b ^. velocity
main :: IO ()
main = do
-- the original ball
let b = Ball { _position = (4.5, 6.2), _velocity = (-0.3, 1.2) }
-- animate the ball by 1 full timestep
let b' = animate b 1
putStrLn $ "Initial ball : " ++ (show b)
putStrLn $ "Animated ball: " ++ (show b')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment