Created
March 18, 2014 14:29
-
-
Save tuttlem/9621183 to your computer and use it in GitHub Desktop.
Lens example
This file contains hidden or 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
{-# 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