SlideShare una empresa de Scribd logo
1 de 33
Introduction to
Lenses in Scala
Introduction to
Lenses in Scala
Shivansh Srivastava
Software Consultant
Knoldus Software LLP
Shivansh Srivastava
Software Consultant
Knoldus Software LLP
AgendaAgenda
● What are Lens?
● Why Lens ?
● Available Implementations.
● Demo.
● What are Lens?
● Why Lens ?
● Available Implementations.
● Demo.
What are LENS ?What are LENS ?
What is Lens ?What is Lens ?
A Lens is an abstraction from functional programming
which helps to deal with a problem of updating complex
immutable nested objects.
Let's start with an example.
case class Turtle(
xcor: Double,
ycor: Double,
heading: Double)
If we want to mutate the value of the heading then.
In the Old Scala Days(2.7):
If we want to mutate the value of the heading then.
In the Old Scala Days(2.7):
case class Turtle(...) {
def right(...): Turtle =
Turtle(xcor,ycor,heading + delta)}
Scala 2.8 comes to the rescue:
case class Turtle(...) {
def right(...): Turtle =
copy(heading = heading + delta)
so far,
so good!
but now...
This is where its needs gets arose.This is where its needs gets arose.
When Nesting plays its partWhen Nesting plays its part
Why Lenses ?Why Lenses ?
Updating mutable
case class Turtle(var ..., ...) {
def forward(dist: Double): Unit = {
position.x += dist * cos(...)
position.y += dist * sin(...)
}
...
Updating (Mutable)
updating
(immutable)
case class Turtle(...) {
def forward(dist: Double): Turtle =
copy(position =
position.copy(
x = position.x +
dist * cos(...),
y = position.y +
dist * sin(...)))
Updating (Immutable)
it gets
worse
case class Turtle(...) {
def forward(dist: Double): Turtle =
this.copy(position =
this.position.copy(
x = this.position.x +
dist * cos(this....),
y = this.position.y +
dist * sin(this....)))
OO Style:
FP style
case class Turtle(...) // no methods
def forward(turtle: Turtle,
dist: Double): Turtle =
turtle.copy(position =
turtle.position.copy(
x = turtle.position.x +
dist * cos(turtle....),
y = turtle.position.y +
dist * sin(turtle....)))
FP Style:
worse
still
n levels deep
// imperative
a.b.c.d.e += 1
// functional
a.copy(
b = a.b.copy(
c = a.b.c.copy(
d = a.b.c.d.copy(
e = a.b.c.d.e +
1))))
What if we go N levels deep:
case class Program(
...
breeds: ListMap[String, Breed] =
ListMap(),
linkBreeds: ListMap[String, Breed] =
ListMap(),
...
)
Production Code:
Production Code:
// if we had lenses this wouldn't get so repetitious
// - ST 7/15/12
if (isLinkBreed)
program.copy(linkBreeds =
orderPreservingUpdate(
program.linkBreeds,
program.linkBreeds(breedName).copy(
owns = newOwns)))
else
program.copy(breeds =
orderPreservingUpdate(
program.breeds,
program.breeds(breedName).copy(
owns = newOwns)))
https://github.com/NetLogo/NetLogo/blob/15700ba6bcab813c5be8b49b8fa00c2204883b08/
headless/src/main/org/nlogo/compiler/StructureParser.scala#L266-L276
We Can Fix it:
omit needless repetition!
avoid nested copy()
The need of the lens arises when there is too much nesting.
If we want to increase userRating in this model then we
will have to write such a code:
If we want to increase userRating in this model then we
will have to write such a code:
And we have to write the code below to confirm all of the
addresses in BillInfo.
And we have to write the code below to confirm all of the
addresses in BillInfo.
If we want to increase userRating in this model then we
will have to write such a code:
If we want to increase userRating in this model then we
will have to write such a code:
If we increase a level of nesting in our structures then we
will considerably increase amount of a code like this. In
such cases lens give a cleaner way to make changes in
nested structures.
Using <<quicklens>> we can do it much simpler:
If we increase a level of nesting in our structures then we
will considerably increase amount of a code like this. In
such cases lens give a cleaner way to make changes in
nested structures.
Using <<quicklens>> we can do it much simpler:
Available ImplementationsAvailable Implementations
There are several implementations in scala:
 scalaz.Lens
 Quicklens
 Sauron
There are several implementations in scala:
 scalaz.Lens
 Quicklens
 Sauron
Available Implementations
If we want to use scalaz.Lens at first we should
define lens:
If we want to use scalaz.Lens at first we should
define lens:
scalaz.Lens:
The first type parameter is needed to set in which class(MainClass)
we will change value and the second type parameter defines the
class(FieldClass) of the field which we will change with the lens.
We should also send two functions to lensu(...) method. The first
function defines how to change MainClass using a new value. The
second function is used to get value of the field which we want to
change.
Quicklens:
Use of scalaz.Lens is quite difficult.It is quite hard and we will
reduce amount of the code only if we have very complex
nesting and implement enough lens to compose them.
Quicklens has support of chain modifications which can be
helpful if you want to change several fields at the same time
It is also possible to create reusable lens as well as
in scalaz.Lens
It is also possible to create reusable lens as well as
in scalaz.Lens
QuickLens:
QuickLens:
And the lens composition is also possible:And the lens composition is also possible:
Sauron:Sauron:
It is said on the main page of Sauron repo it has been inspired
by quicklens but it has much simpler implementation and less
number of features. And also has additional dependency on
"org.scalamacros" % "paradise" % "2.1.0-M5"
Sauron:Sauron:
The example below shows how to define lens for
changing different objects:
Sauron:Sauron:
The example below shows hot to define lens for changing
different objects:
Results:
➔ scalaz.Lens - If you already have scalaz in a project
and you are not bothered to write some code in order
to define lens
➔ Quicklens - Easy to use and powerful enough to deal
with the described problem
➔ Sauron - Very similar to Quicklens and has a less size
but also has less functionality
Refrences:Refrences:
 www.koff.io
 Slides by Seth Tisue in ScalaDays 2013
 https://github.com/pathikrit/sauron
 https://github.com/adamw/quicklens
Thanks..!!Thanks..!!

Más contenido relacionado

La actualidad más candente

Servlet & JSP 教學手冊第二版試讀 - 撰寫與設定 Servlet
Servlet & JSP 教學手冊第二版試讀 - 撰寫與設定 ServletServlet & JSP 教學手冊第二版試讀 - 撰寫與設定 Servlet
Servlet & JSP 教學手冊第二版試讀 - 撰寫與設定 Servlet
Justin Lin
 

La actualidad más candente (20)

Spring Boot
Spring BootSpring Boot
Spring Boot
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Dependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalDependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functional
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and Annotations
 
4. 대용량 아키텍쳐 설계 패턴
4. 대용량 아키텍쳐 설계 패턴4. 대용량 아키텍쳐 설계 패턴
4. 대용량 아키텍쳐 설계 패턴
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
JVM Under The Hood WDI.pdf
JVM Under The Hood WDI.pdfJVM Under The Hood WDI.pdf
JVM Under The Hood WDI.pdf
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Serverless Machine Learning Model Inference on Kubernetes with KServe.pdf
Serverless Machine Learning Model Inference on Kubernetes with KServe.pdfServerless Machine Learning Model Inference on Kubernetes with KServe.pdf
Serverless Machine Learning Model Inference on Kubernetes with KServe.pdf
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
How and Why GraalVM is quickly becoming relevant for developers (ACEs@home - ...
How and Why GraalVM is quickly becoming relevant for developers (ACEs@home - ...How and Why GraalVM is quickly becoming relevant for developers (ACEs@home - ...
How and Why GraalVM is quickly becoming relevant for developers (ACEs@home - ...
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Servlet & JSP 教學手冊第二版試讀 - 撰寫與設定 Servlet
Servlet & JSP 教學手冊第二版試讀 - 撰寫與設定 ServletServlet & JSP 教學手冊第二版試讀 - 撰寫與設定 Servlet
Servlet & JSP 教學手冊第二版試讀 - 撰寫與設定 Servlet
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
From Spring Framework 5.3 to 6.0
From Spring Framework 5.3 to 6.0From Spring Framework 5.3 to 6.0
From Spring Framework 5.3 to 6.0
 
devoxx 2022 - 10 ans de Devoxx FR et de Java.pdf
devoxx 2022 - 10 ans de Devoxx FR et de Java.pdfdevoxx 2022 - 10 ans de Devoxx FR et de Java.pdf
devoxx 2022 - 10 ans de Devoxx FR et de Java.pdf
 

Destacado

こわくない型クラス
こわくない型クラスこわくない型クラス
こわくない型クラス
Kota Mizushima
 

Destacado (10)

Beyond Scala Lens
Beyond Scala LensBeyond Scala Lens
Beyond Scala Lens
 
Optics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeOptics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the whole
 
λ | Lenses
λ | Lensesλ | Lenses
λ | Lenses
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functional
 
Scalaで実装するGC
Scalaで実装するGCScalaで実装するGC
Scalaで実装するGC
 
こわくない型クラス
こわくない型クラスこわくない型クラス
こわくない型クラス
 
Scalaz
ScalazScalaz
Scalaz
 
Scalaで型クラス入門
Scalaで型クラス入門Scalaで型クラス入門
Scalaで型クラス入門
 
Grokking Monads in Scala
Grokking Monads in ScalaGrokking Monads in Scala
Grokking Monads in Scala
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless
 

Similar a Scala lens: An introduction

scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
Scala Italy
 

Similar a Scala lens: An introduction (20)

Devoxx
DevoxxDevoxx
Devoxx
 
Play framework
Play frameworkPlay framework
Play framework
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
 
Scala's evolving ecosystem- Introduction to Scala.js
Scala's evolving ecosystem- Introduction to Scala.jsScala's evolving ecosystem- Introduction to Scala.js
Scala's evolving ecosystem- Introduction to Scala.js
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
 
Martin Odersky: What's next for Scala
Martin Odersky: What's next for ScalaMartin Odersky: What's next for Scala
Martin Odersky: What's next for Scala
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the Covers
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 
Create a new project in ROR
Create a new project in RORCreate a new project in ROR
Create a new project in ROR
 
Angular JS in 2017
Angular JS in 2017Angular JS in 2017
Angular JS in 2017
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
 
Jaoo Michael Neale 09
Jaoo Michael Neale 09Jaoo Michael Neale 09
Jaoo Michael Neale 09
 
RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - Keynote
 

Más de Knoldus Inc.

Más de Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Último

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 

Último (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Scala lens: An introduction

  • 1. Introduction to Lenses in Scala Introduction to Lenses in Scala Shivansh Srivastava Software Consultant Knoldus Software LLP Shivansh Srivastava Software Consultant Knoldus Software LLP
  • 2. AgendaAgenda ● What are Lens? ● Why Lens ? ● Available Implementations. ● Demo. ● What are Lens? ● Why Lens ? ● Available Implementations. ● Demo.
  • 3. What are LENS ?What are LENS ?
  • 4. What is Lens ?What is Lens ? A Lens is an abstraction from functional programming which helps to deal with a problem of updating complex immutable nested objects. Let's start with an example. case class Turtle( xcor: Double, ycor: Double, heading: Double)
  • 5. If we want to mutate the value of the heading then. In the Old Scala Days(2.7): If we want to mutate the value of the heading then. In the Old Scala Days(2.7): case class Turtle(...) { def right(...): Turtle = Turtle(xcor,ycor,heading + delta)} Scala 2.8 comes to the rescue: case class Turtle(...) { def right(...): Turtle = copy(heading = heading + delta)
  • 7. This is where its needs gets arose.This is where its needs gets arose. When Nesting plays its partWhen Nesting plays its part
  • 8. Why Lenses ?Why Lenses ?
  • 9. Updating mutable case class Turtle(var ..., ...) { def forward(dist: Double): Unit = { position.x += dist * cos(...) position.y += dist * sin(...) } ... Updating (Mutable)
  • 10. updating (immutable) case class Turtle(...) { def forward(dist: Double): Turtle = copy(position = position.copy( x = position.x + dist * cos(...), y = position.y + dist * sin(...))) Updating (Immutable)
  • 12. case class Turtle(...) { def forward(dist: Double): Turtle = this.copy(position = this.position.copy( x = this.position.x + dist * cos(this....), y = this.position.y + dist * sin(this....))) OO Style:
  • 13. FP style case class Turtle(...) // no methods def forward(turtle: Turtle, dist: Double): Turtle = turtle.copy(position = turtle.position.copy( x = turtle.position.x + dist * cos(turtle....), y = turtle.position.y + dist * sin(turtle....))) FP Style:
  • 15. n levels deep // imperative a.b.c.d.e += 1 // functional a.copy( b = a.b.copy( c = a.b.c.copy( d = a.b.c.d.copy( e = a.b.c.d.e + 1)))) What if we go N levels deep:
  • 16. case class Program( ... breeds: ListMap[String, Breed] = ListMap(), linkBreeds: ListMap[String, Breed] = ListMap(), ... ) Production Code:
  • 17. Production Code: // if we had lenses this wouldn't get so repetitious // - ST 7/15/12 if (isLinkBreed) program.copy(linkBreeds = orderPreservingUpdate( program.linkBreeds, program.linkBreeds(breedName).copy( owns = newOwns))) else program.copy(breeds = orderPreservingUpdate( program.breeds, program.breeds(breedName).copy( owns = newOwns))) https://github.com/NetLogo/NetLogo/blob/15700ba6bcab813c5be8b49b8fa00c2204883b08/ headless/src/main/org/nlogo/compiler/StructureParser.scala#L266-L276
  • 18. We Can Fix it: omit needless repetition! avoid nested copy()
  • 19. The need of the lens arises when there is too much nesting.
  • 20. If we want to increase userRating in this model then we will have to write such a code: If we want to increase userRating in this model then we will have to write such a code: And we have to write the code below to confirm all of the addresses in BillInfo. And we have to write the code below to confirm all of the addresses in BillInfo. If we want to increase userRating in this model then we will have to write such a code: If we want to increase userRating in this model then we will have to write such a code:
  • 21. If we increase a level of nesting in our structures then we will considerably increase amount of a code like this. In such cases lens give a cleaner way to make changes in nested structures. Using <<quicklens>> we can do it much simpler: If we increase a level of nesting in our structures then we will considerably increase amount of a code like this. In such cases lens give a cleaner way to make changes in nested structures. Using <<quicklens>> we can do it much simpler:
  • 23. There are several implementations in scala:  scalaz.Lens  Quicklens  Sauron There are several implementations in scala:  scalaz.Lens  Quicklens  Sauron Available Implementations
  • 24. If we want to use scalaz.Lens at first we should define lens: If we want to use scalaz.Lens at first we should define lens: scalaz.Lens: The first type parameter is needed to set in which class(MainClass) we will change value and the second type parameter defines the class(FieldClass) of the field which we will change with the lens. We should also send two functions to lensu(...) method. The first function defines how to change MainClass using a new value. The second function is used to get value of the field which we want to change.
  • 25. Quicklens: Use of scalaz.Lens is quite difficult.It is quite hard and we will reduce amount of the code only if we have very complex nesting and implement enough lens to compose them. Quicklens has support of chain modifications which can be helpful if you want to change several fields at the same time
  • 26. It is also possible to create reusable lens as well as in scalaz.Lens It is also possible to create reusable lens as well as in scalaz.Lens QuickLens:
  • 27. QuickLens: And the lens composition is also possible:And the lens composition is also possible:
  • 28. Sauron:Sauron: It is said on the main page of Sauron repo it has been inspired by quicklens but it has much simpler implementation and less number of features. And also has additional dependency on "org.scalamacros" % "paradise" % "2.1.0-M5"
  • 29. Sauron:Sauron: The example below shows how to define lens for changing different objects:
  • 30. Sauron:Sauron: The example below shows hot to define lens for changing different objects:
  • 31. Results: ➔ scalaz.Lens - If you already have scalaz in a project and you are not bothered to write some code in order to define lens ➔ Quicklens - Easy to use and powerful enough to deal with the described problem ➔ Sauron - Very similar to Quicklens and has a less size but also has less functionality
  • 32. Refrences:Refrences:  www.koff.io  Slides by Seth Tisue in ScalaDays 2013  https://github.com/pathikrit/sauron  https://github.com/adamw/quicklens

Notas del editor

  1. many web application want to increase application throughput, responsivenesswhere one task can make progress without waiting for all others to completewhere more than one task can make progress at same time.Concurrent program can be executed on single core machine via time slicYou may execute concurrent program in parallelOverall you play with threads