SlideShare a Scribd company logo
Lenses 
Maxim Kulkin
Why Lenses?
Data types in Haskell 
! 
! 
! 
data Person = Person String Int 
! 
let john = Person “John” 35 
let will = Person “William” 28
Accessing fields 
! 
! 
let Person name age = john 
— pattern match with `let` 
putStrLn (“Hello, “ ++ name) 
! 
personName :: Person -> String 
personName (Person name _) = name 
! 
personAge :: Person -> Int 
personAge (Person _ age) = age
Changing field data 
! 
! 
! 
setPersonName :: Person -> String -> Person 
setPersonName (Person _ age) newName = 
Person newName age 
! 
setPersonAge :: Person -> Int -> Person 
setPersonAge (Person name _) newAge = 
Person name newAge
Record Syntax 
data Person = Person 
{ personName :: String 
, personAge :: Int 
} 
! 
let john = Person “John” 35 
let will = Person { personName = “William 
, personAge = 28 
} 
! 
personName john — => “John” 
personAge john — => 35 
! 
itsABirthday :: Person -> Person 
itsABirthday person = 
person { personAge = personAge person + 1 }
Traversing data 
! 
data Point = Point { x :: Int, y :: Int } 
data Unit = Unit { health :: Int, position :: Point } 
! 
let pacman = Unit { health = 10, position = Point 0 0 } 
let ghost = Unit { health = 1, position = Point 5 3 } 
! 
moveLeftBy :: Int -> Unit -> Unit 
moveLeftBy v unit = let pos = position unit 
pos’ = pos { x = x pos - v } 
in unit { position = pos’ }
Introducing Lenses 
! 
data Lens s a = Lens { view :: s -> a 
, set :: s -> a -> s 
} 
! 
personName :: Lens Person String 
personAge :: Lens Person Int 
! 
view personName john 
— => “John” 
set personName “John Doe” john 
— => Person “John Doe” 35
Lens Laws 
• Get-Put: view l (set l v s) = v 
You get back what you put in! 
• Put-Get: set l (view l s) s = s 
Putting back what you got doesn’t change anything 
• Put-Put: set l v’ (set l v s) = set l v’ s 
Setting twice is the same as setting once
Operations 
! 
! 
! 
view :: Lens s a -> s -> a 
! 
set :: Lens s a -> a -> s -> s 
! 
over :: Lens s a -> (a -> a) -> s -> s
Composition 
— Function composition 
(.) :: (b -> c) -> (a -> b) -> (a -> c) 
! 
! 
— Lens composition 
lens1 :: Lens a b 
lens2 :: Lens b c 
! 
lens1 . lens2 :: Lens a c 
! 
— Example 
moveLeftBy v unit = over (position.x) (+v) unit 
! 
unitX :: Lens Unit Int 
unitX = position.x
Those are naive 
lenses
Introducing Lenses (2) 
! 
type Lens s t a b = 
forall f. Functor f => (a -> f b) -> s -> f t 
! 
Allows changing result type 
! 
type Lens’ s a = Lens s s a a — simple lens 
! 
Because lenses are just functions, 
function composition works without any extra 
effort
Creating Lenses 
data Point = Point { _pointX :: Int 
, _pointY :: Int 
} 
! 
lens :: (s -> a) -> (s -> b -> t) -> Lens s t a b 
— Allows creating lens from getter and setter 
! 
pointX :: Lens’ Point Int 
pointX = lens _pointX (p x -> p { _pointX = x }) 
! 
! 
{-# LANGUAGE TemplateHaskell #-} 
makeLenses ‘’Point
Some Lens Operations 
(^.) :: Lens s t a b -> s -> a 
— Infix version of `view` 
— ghost^.position.x 
! 
(.~) :: Lens s t a b -> b -> s -> t 
— Infix version of `set` 
— pacman & position.x .~ 10 
! 
(%~) :: Lens s t a b -> (a -> b) -> s -> t 
— Infix version of `over` 
— pacman & position.x %~ (+10) 
! 
(+~) :: Num a => Lens s t a b -> a -> s -> t 
— Increment the target of a numerically valued Lens 
— pacman & position.x +~ 10
MonadState operators 
Most operators have a MonadState counterpart, e.g: 
! 
! 
! 
(.=) :: MonadState s m => Lens’ s a -> a -> m ()
Why changing types? 
! 
— Example: lenses for tuples 
! 
_1 :: Lens (a,b) (a',b) a a’ 
! 
_2 :: Lens (a,b) (a,b’) b b’
Prisms 
They’re like lenses for sum types 
data Either e a = Left e | Right a 
! 
_Left :: Prism’ (Either a b) a 
_Right :: Prism’ (Either a b) b 
! 
! 
— go down 
preview :: Prism’ s a -> s -> Maybe a 
! 
— go up 
review :: Prism’ s a -> a -> s
Prisms 
_Left :: Prism’ (Either a b) a 
! 
>>> preview _Left (Left “hi”) 
Just “hi” 
! 
>>> preview _Left (Right “hi”) 
Nothing 
! 
>>> review _Left “hi” 
Left “hi” 
! 
>>> Left “hi” ^? _Left 
Just “hi”
Prism examples 
_Cons :: Prism' [a] (a, [a]) 
! 
>>> preview _Cons [] 
Nothing 
! 
>>> preview _Cons [1,2,3] 
Just (1, [2,3]) 
! 
_Nil :: Prism' [a] () 
! 
>>> preview _Nil [] 
Just () 
! 
>>> preview _Nil [1,2,3] 
Nothing 
_ParseTrue :: Prism' String Bool 
_ParseFalse :: Prism' String Bool 
! 
>>> preview _ParseTrue "True" 
Just True 
! 
>>> preview _ParseFalse "True" 
Nothing 
! 
>>> review _ParseTrue True 
"True"
Traversals and Folds 
Traversable - generalization of traverse, allows you to traverse over 
a structure and change out its contents! 
! 
Foldable - generalization of something Foldable, allows you to extract 
multiple results from a container! 
!! 
traversed :: Traversable f => IndexedTraversal Int (f a) (f b) a b! 
folded :: Foldable f => IndexedFold Int (f a) a! 
! 
(^..) :: s -> Traversal’ s a -> [a]! 
(^..) :: s -> Fold s a -> [a]! 
!! 
>>> sumOf folded [1,2,3,4]! 
10! 
>>> sumOf (folded.traversed) [[1,2], [3,4]]! 
10! 
>>> maximumOf (folded.filtered even) [1,4,3,6,7,9,2]! 
Just 6
Example: Game 
{-# LANGUAGE TemplateHaskell #-}! 
! 
import Control.Lens! 
! 
data Game = Game! 
{ _score :: Int! 
, _units :: [Unit]! 
, _boss :: Unit! 
} deriving (Show)! 
! 
data Unit = Unit! 
{ _health :: Int! 
, _position :: Point! 
} deriving (Show)! 
! 
data Point = Point! 
{ _x :: Double! 
, _y :: Double! 
} deriving (Show)! 
! 
makeLenses ''Game! 
makeLenses ''Unit! 
makeLenses ''Point
Example: Game 
initialState :: Game! 
initialState = Game! 
{ _score = 0! 
, _units =! 
[ Unit! 
{ _health = 10! 
, _position = Point { _x = 3.5, _y = 7.0 }! 
}! 
, Unit! 
{ _health = 15! 
, _position = Point { _x = 1.0, _y = 1.0 }! 
}! 
, Unit! 
{ _health = 8! 
, _position = Point { _x = 0.0, _y = 2.1 }! 
}! 
]! 
, _boss = Unit! 
{ _health = 100! 
, _position = Point { _x = 0.0, _y = 0.0 }! 
}! 
}
Example: Game 
import Control.Monad.Trans.Class! 
import Control.Monad.Trans.State! 
! 
strike :: StateT Game IO ()! 
strike = do! 
lift $ putStrLn "*shink*"! 
boss.health -= 10! 
!!! 
>>> newState <- execStateT strike initialState ! 
*shink*! 
! 
>>> newState^.boss.health! 
90
Example: Game 
units :: Lens' Game [Unit]! 
units.traversed :: Traversal' Game Unit! 
units.traversed.health :: Traversal' Game Int! 
!!! 
partyHP :: Traversal' Game Int! 
partyHP = units.traversed.health! 
! 
fireBreath :: StateT Game IO ()! 
fireBreath = do! 
lift $ putStrLn "*rawr*"! 
partyHP -= 3! 
!! 
>>> initialState^..partyHP! 
[10,15,8]! 
! 
>>> newState <- execStateT fireBreath initialState ! 
! 
>>> newState^..partyHP! 
[7,12,5]
Example: Game 
around :: Point -> Double -> Traversal' Unit Unit! 
around center radius = filtered (unit ->! 
(unit^.position.x - center^.x)^2! 
+ (unit^.position.y - center^.y)^2! 
< radius^2 )! 
! 
fireBreath :: Point -> StateT Game IO ()! 
fireBreath target = do! 
lift $ putStrLn "*rawr*"! 
units.traversed.(around target 1.0).health -= 3
Example: Game 
partyLoc :: Traversal' Game Point! 
partyLoc = units.traversed.position! 
! 
retreat :: StateT Game IO ()! 
retreat = do! 
lift $ putStrLn "Retreat!"! 
zoom partyLoc $ do! 
x += 10! 
y += 10
Example: Game 
battle :: StateT Game IO ()! 
battle = do! 
-- Charge!! 
forM_ ["Take that!", "and that!", 
"and that!"] $ taunt -> do! 
lift $ putStrLn taunt! 
strike! 
! 
-- The dragon awakes!! 
fireBreath (Point 0.5 1.5)! 
! 
replicateM_ 3 $ do! 
-- The better part of valor! 
retreat! 
! 
-- Boss chases them! 
zoom (boss.position) $ do! 
x += 10! 
y += 10 
>>> execStateT battle initialState ! 
Take that!! 
*shink*! 
and that!! 
*shink*! 
and that!! 
*shink*! 
*rawr*! 
Retreat!! 
Retreat!! 
Retreat!! 
Game {_score = 0, _units = [Unit {_health 
= 10, _position = Poin! 
t {_x = 33.5, _y = 37.0}},Unit {_health = 
12, _position = Point ! 
{_x = 31.0, _y = 31.0}},Unit {_health = 
5, _position = Point {_x! 
= 30.0, _y = 32.1}}], _boss = Unit 
{_health = 70, _position = P! 
oint {_x = 30.0, _y = 30.0}}}
References 
• FPComplete Lens Tutorial 
https://www.fpcomplete.com/school/to-infinity-and-beyond/pick-of-the-week/a-little-lens- 
starter-tutorial 
• Programming imperatively using Haskell 
http://www.haskellforall.com/2013/05/program-imperatively-using-haskell.html 
• Lenses, Folds and Traversals 
http://lens.github.io 
• Lenses In Pictures 
http://adit.io/posts/2013-07-22-lenses-in-pictures.html
Thank you!

More Related Content

What's hot

What's hot (20)

Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't Free
 
Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)
 
Millionways
MillionwaysMillionways
Millionways
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
 
Oh Composable World!
Oh Composable World!Oh Composable World!
Oh Composable World!
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
Acm
AcmAcm
Acm
 
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
 
The Ring programming language version 1.7 book - Part 57 of 196
The Ring programming language version 1.7 book - Part 57 of 196The Ring programming language version 1.7 book - Part 57 of 196
The Ring programming language version 1.7 book - Part 57 of 196
 
ES6 and AngularAMD
ES6 and AngularAMDES6 and AngularAMD
ES6 and AngularAMD
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional Programming
 

Viewers also liked

Arabic alphabatical list
Arabic alphabatical listArabic alphabatical list
Arabic alphabatical list
Khalid Hadari
 
αρχαϊκη τα γράμματα
αρχαϊκη  τα γράμματααρχαϊκη  τα γράμματα
αρχαϊκη τα γράμματα
4444465
 

Viewers also liked (19)

Scala lens: An introduction
Scala lens: An introductionScala lens: An introduction
Scala lens: An introduction
 
Mpdf (3)
Mpdf (3)Mpdf (3)
Mpdf (3)
 
Dressed to the nines
Dressed to the ninesDressed to the nines
Dressed to the nines
 
Summerschool Heelkunde UGent 2013
Summerschool Heelkunde UGent 2013Summerschool Heelkunde UGent 2013
Summerschool Heelkunde UGent 2013
 
A sustainable population essay for dynamic singapore by StudentsAssignmentHe...
A sustainable population essay for  dynamic singapore by StudentsAssignmentHe...A sustainable population essay for  dynamic singapore by StudentsAssignmentHe...
A sustainable population essay for dynamic singapore by StudentsAssignmentHe...
 
Top indicators shaping your permission based marketing databases
Top indicators shaping your permission based marketing databasesTop indicators shaping your permission based marketing databases
Top indicators shaping your permission based marketing databases
 
The gift guide for all your girlfriends
The gift guide for all your girlfriendsThe gift guide for all your girlfriends
The gift guide for all your girlfriends
 
School Project, Physics
School Project, Physics School Project, Physics
School Project, Physics
 
Curso de office
Curso de officeCurso de office
Curso de office
 
Введение в Apache Cassandra
Введение в Apache CassandraВведение в Apache Cassandra
Введение в Apache Cassandra
 
Why to Consider Account Based Marketing?
Why to Consider Account Based Marketing?Why to Consider Account Based Marketing?
Why to Consider Account Based Marketing?
 
Arabic alphabatical list
Arabic alphabatical listArabic alphabatical list
Arabic alphabatical list
 
Udine3D Forum - novembre 2015
Udine3D Forum - novembre 2015Udine3D Forum - novembre 2015
Udine3D Forum - novembre 2015
 
Akka и реактивное программирование на JVM
Akka и реактивное программирование на JVMAkka и реактивное программирование на JVM
Akka и реактивное программирование на JVM
 
Spot 2
Spot 2Spot 2
Spot 2
 
Sfida #1: Tecnologia e Didattica
Sfida #1: Tecnologia e DidatticaSfida #1: Tecnologia e Didattica
Sfida #1: Tecnologia e Didattica
 
αρχαϊκη τα γράμματα
αρχαϊκη  τα γράμματααρχαϊκη  τα γράμματα
αρχαϊκη τα γράμματα
 
bucaramanga
bucaramanga bucaramanga
bucaramanga
 
Виртуализация как инструмент разработчика
Виртуализация как инструмент разработчикаВиртуализация как инструмент разработчика
Виртуализация как инструмент разработчика
 

Similar to λ | Lenses

Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
aztack
 

Similar to λ | Lenses (20)

Python
PythonPython
Python
 
Python 1
Python 1Python 1
Python 1
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
Frege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMFrege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVM
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
 
Combinator parsing
Combinator parsingCombinator parsing
Combinator parsing
 
Investigating Python Wats
Investigating Python WatsInvestigating Python Wats
Investigating Python Wats
 
Corona sdk
Corona sdkCorona sdk
Corona sdk
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library design
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
Python seaborn cheat_sheet
Python seaborn cheat_sheetPython seaborn cheat_sheet
Python seaborn cheat_sheet
 
Add Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJSAdd Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJS
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 

More from Open-IT

Microsoft kinect
Microsoft kinectMicrosoft kinect
Microsoft kinect
Open-IT
 
Сам себе АНБ, API социальных сетей
Сам себе АНБ, API социальных сетейСам себе АНБ, API социальных сетей
Сам себе АНБ, API социальных сетей
Open-IT
 
Talkbits service architecture and deployment
Talkbits service architecture and deploymentTalkbits service architecture and deployment
Talkbits service architecture and deployment
Open-IT
 

More from Open-IT (10)

How to make friends python with win32 api
How to make friends python with win32 apiHow to make friends python with win32 api
How to make friends python with win32 api
 
Mathematical optimization and python
Mathematical optimization and pythonMathematical optimization and python
Mathematical optimization and python
 
Секретный доклад
Секретный докладСекретный доклад
Секретный доклад
 
Rust: абстракции и безопасность, совершенно бесплатно
Rust: абстракции и безопасность, совершенно бесплатноRust: абстракции и безопасность, совершенно бесплатно
Rust: абстракции и безопасность, совершенно бесплатно
 
Cooking Cassandra
Cooking CassandraCooking Cassandra
Cooking Cassandra
 
Командная разработка “толстых клиентов”
Командная разработка “толстых клиентов”Командная разработка “толстых клиентов”
Командная разработка “толстых клиентов”
 
Fuel's current use cases, architecture and next steps
Fuel's current use cases, architecture and next stepsFuel's current use cases, architecture and next steps
Fuel's current use cases, architecture and next steps
 
Microsoft kinect
Microsoft kinectMicrosoft kinect
Microsoft kinect
 
Сам себе АНБ, API социальных сетей
Сам себе АНБ, API социальных сетейСам себе АНБ, API социальных сетей
Сам себе АНБ, API социальных сетей
 
Talkbits service architecture and deployment
Talkbits service architecture and deploymentTalkbits service architecture and deployment
Talkbits service architecture and deployment
 

Recently uploaded

Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
Kamal Acharya
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
Kamal Acharya
 
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
Kamal Acharya
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
Kamal Acharya
 

Recently uploaded (20)

Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
 
AI for workflow automation Use cases applications benefits and development.pdf
AI for workflow automation Use cases applications benefits and development.pdfAI for workflow automation Use cases applications benefits and development.pdf
AI for workflow automation Use cases applications benefits and development.pdf
 
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and ClusteringKIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
 
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGBRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering Workshop
 
Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltage
 
retail automation billing system ppt.pptx
retail automation billing system ppt.pptxretail automation billing system ppt.pptx
retail automation billing system ppt.pptx
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
 
Furniture showroom management system project.pdf
Furniture showroom management system project.pdfFurniture showroom management system project.pdf
Furniture showroom management system project.pdf
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
 
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
 
Peek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdfPeek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdf
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptx
 
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and VisualizationKIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
 
Introduction to Casting Processes in Manufacturing
Introduction to Casting Processes in ManufacturingIntroduction to Casting Processes in Manufacturing
Introduction to Casting Processes in Manufacturing
 
Construction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxConstruction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptx
 

λ | Lenses

  • 3. Data types in Haskell ! ! ! data Person = Person String Int ! let john = Person “John” 35 let will = Person “William” 28
  • 4. Accessing fields ! ! let Person name age = john — pattern match with `let` putStrLn (“Hello, “ ++ name) ! personName :: Person -> String personName (Person name _) = name ! personAge :: Person -> Int personAge (Person _ age) = age
  • 5. Changing field data ! ! ! setPersonName :: Person -> String -> Person setPersonName (Person _ age) newName = Person newName age ! setPersonAge :: Person -> Int -> Person setPersonAge (Person name _) newAge = Person name newAge
  • 6. Record Syntax data Person = Person { personName :: String , personAge :: Int } ! let john = Person “John” 35 let will = Person { personName = “William , personAge = 28 } ! personName john — => “John” personAge john — => 35 ! itsABirthday :: Person -> Person itsABirthday person = person { personAge = personAge person + 1 }
  • 7. Traversing data ! data Point = Point { x :: Int, y :: Int } data Unit = Unit { health :: Int, position :: Point } ! let pacman = Unit { health = 10, position = Point 0 0 } let ghost = Unit { health = 1, position = Point 5 3 } ! moveLeftBy :: Int -> Unit -> Unit moveLeftBy v unit = let pos = position unit pos’ = pos { x = x pos - v } in unit { position = pos’ }
  • 8. Introducing Lenses ! data Lens s a = Lens { view :: s -> a , set :: s -> a -> s } ! personName :: Lens Person String personAge :: Lens Person Int ! view personName john — => “John” set personName “John Doe” john — => Person “John Doe” 35
  • 9. Lens Laws • Get-Put: view l (set l v s) = v You get back what you put in! • Put-Get: set l (view l s) s = s Putting back what you got doesn’t change anything • Put-Put: set l v’ (set l v s) = set l v’ s Setting twice is the same as setting once
  • 10. Operations ! ! ! view :: Lens s a -> s -> a ! set :: Lens s a -> a -> s -> s ! over :: Lens s a -> (a -> a) -> s -> s
  • 11. Composition — Function composition (.) :: (b -> c) -> (a -> b) -> (a -> c) ! ! — Lens composition lens1 :: Lens a b lens2 :: Lens b c ! lens1 . lens2 :: Lens a c ! — Example moveLeftBy v unit = over (position.x) (+v) unit ! unitX :: Lens Unit Int unitX = position.x
  • 12. Those are naive lenses
  • 13. Introducing Lenses (2) ! type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t ! Allows changing result type ! type Lens’ s a = Lens s s a a — simple lens ! Because lenses are just functions, function composition works without any extra effort
  • 14. Creating Lenses data Point = Point { _pointX :: Int , _pointY :: Int } ! lens :: (s -> a) -> (s -> b -> t) -> Lens s t a b — Allows creating lens from getter and setter ! pointX :: Lens’ Point Int pointX = lens _pointX (p x -> p { _pointX = x }) ! ! {-# LANGUAGE TemplateHaskell #-} makeLenses ‘’Point
  • 15. Some Lens Operations (^.) :: Lens s t a b -> s -> a — Infix version of `view` — ghost^.position.x ! (.~) :: Lens s t a b -> b -> s -> t — Infix version of `set` — pacman & position.x .~ 10 ! (%~) :: Lens s t a b -> (a -> b) -> s -> t — Infix version of `over` — pacman & position.x %~ (+10) ! (+~) :: Num a => Lens s t a b -> a -> s -> t — Increment the target of a numerically valued Lens — pacman & position.x +~ 10
  • 16. MonadState operators Most operators have a MonadState counterpart, e.g: ! ! ! (.=) :: MonadState s m => Lens’ s a -> a -> m ()
  • 17. Why changing types? ! — Example: lenses for tuples ! _1 :: Lens (a,b) (a',b) a a’ ! _2 :: Lens (a,b) (a,b’) b b’
  • 18. Prisms They’re like lenses for sum types data Either e a = Left e | Right a ! _Left :: Prism’ (Either a b) a _Right :: Prism’ (Either a b) b ! ! — go down preview :: Prism’ s a -> s -> Maybe a ! — go up review :: Prism’ s a -> a -> s
  • 19. Prisms _Left :: Prism’ (Either a b) a ! >>> preview _Left (Left “hi”) Just “hi” ! >>> preview _Left (Right “hi”) Nothing ! >>> review _Left “hi” Left “hi” ! >>> Left “hi” ^? _Left Just “hi”
  • 20. Prism examples _Cons :: Prism' [a] (a, [a]) ! >>> preview _Cons [] Nothing ! >>> preview _Cons [1,2,3] Just (1, [2,3]) ! _Nil :: Prism' [a] () ! >>> preview _Nil [] Just () ! >>> preview _Nil [1,2,3] Nothing _ParseTrue :: Prism' String Bool _ParseFalse :: Prism' String Bool ! >>> preview _ParseTrue "True" Just True ! >>> preview _ParseFalse "True" Nothing ! >>> review _ParseTrue True "True"
  • 21. Traversals and Folds Traversable - generalization of traverse, allows you to traverse over a structure and change out its contents! ! Foldable - generalization of something Foldable, allows you to extract multiple results from a container! !! traversed :: Traversable f => IndexedTraversal Int (f a) (f b) a b! folded :: Foldable f => IndexedFold Int (f a) a! ! (^..) :: s -> Traversal’ s a -> [a]! (^..) :: s -> Fold s a -> [a]! !! >>> sumOf folded [1,2,3,4]! 10! >>> sumOf (folded.traversed) [[1,2], [3,4]]! 10! >>> maximumOf (folded.filtered even) [1,4,3,6,7,9,2]! Just 6
  • 22. Example: Game {-# LANGUAGE TemplateHaskell #-}! ! import Control.Lens! ! data Game = Game! { _score :: Int! , _units :: [Unit]! , _boss :: Unit! } deriving (Show)! ! data Unit = Unit! { _health :: Int! , _position :: Point! } deriving (Show)! ! data Point = Point! { _x :: Double! , _y :: Double! } deriving (Show)! ! makeLenses ''Game! makeLenses ''Unit! makeLenses ''Point
  • 23. Example: Game initialState :: Game! initialState = Game! { _score = 0! , _units =! [ Unit! { _health = 10! , _position = Point { _x = 3.5, _y = 7.0 }! }! , Unit! { _health = 15! , _position = Point { _x = 1.0, _y = 1.0 }! }! , Unit! { _health = 8! , _position = Point { _x = 0.0, _y = 2.1 }! }! ]! , _boss = Unit! { _health = 100! , _position = Point { _x = 0.0, _y = 0.0 }! }! }
  • 24. Example: Game import Control.Monad.Trans.Class! import Control.Monad.Trans.State! ! strike :: StateT Game IO ()! strike = do! lift $ putStrLn "*shink*"! boss.health -= 10! !!! >>> newState <- execStateT strike initialState ! *shink*! ! >>> newState^.boss.health! 90
  • 25. Example: Game units :: Lens' Game [Unit]! units.traversed :: Traversal' Game Unit! units.traversed.health :: Traversal' Game Int! !!! partyHP :: Traversal' Game Int! partyHP = units.traversed.health! ! fireBreath :: StateT Game IO ()! fireBreath = do! lift $ putStrLn "*rawr*"! partyHP -= 3! !! >>> initialState^..partyHP! [10,15,8]! ! >>> newState <- execStateT fireBreath initialState ! ! >>> newState^..partyHP! [7,12,5]
  • 26. Example: Game around :: Point -> Double -> Traversal' Unit Unit! around center radius = filtered (unit ->! (unit^.position.x - center^.x)^2! + (unit^.position.y - center^.y)^2! < radius^2 )! ! fireBreath :: Point -> StateT Game IO ()! fireBreath target = do! lift $ putStrLn "*rawr*"! units.traversed.(around target 1.0).health -= 3
  • 27. Example: Game partyLoc :: Traversal' Game Point! partyLoc = units.traversed.position! ! retreat :: StateT Game IO ()! retreat = do! lift $ putStrLn "Retreat!"! zoom partyLoc $ do! x += 10! y += 10
  • 28. Example: Game battle :: StateT Game IO ()! battle = do! -- Charge!! forM_ ["Take that!", "and that!", "and that!"] $ taunt -> do! lift $ putStrLn taunt! strike! ! -- The dragon awakes!! fireBreath (Point 0.5 1.5)! ! replicateM_ 3 $ do! -- The better part of valor! retreat! ! -- Boss chases them! zoom (boss.position) $ do! x += 10! y += 10 >>> execStateT battle initialState ! Take that!! *shink*! and that!! *shink*! and that!! *shink*! *rawr*! Retreat!! Retreat!! Retreat!! Game {_score = 0, _units = [Unit {_health = 10, _position = Poin! t {_x = 33.5, _y = 37.0}},Unit {_health = 12, _position = Point ! {_x = 31.0, _y = 31.0}},Unit {_health = 5, _position = Point {_x! = 30.0, _y = 32.1}}], _boss = Unit {_health = 70, _position = P! oint {_x = 30.0, _y = 30.0}}}
  • 29. References • FPComplete Lens Tutorial https://www.fpcomplete.com/school/to-infinity-and-beyond/pick-of-the-week/a-little-lens- starter-tutorial • Programming imperatively using Haskell http://www.haskellforall.com/2013/05/program-imperatively-using-haskell.html • Lenses, Folds and Traversals http://lens.github.io • Lenses In Pictures http://adit.io/posts/2013-07-22-lenses-in-pictures.html