SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
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..!!

Contenu connexe

Tendances

Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...
Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...
Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...Edureka!
 
Docker & Kubernetes 기초 - 최용호
Docker & Kubernetes 기초 - 최용호Docker & Kubernetes 기초 - 최용호
Docker & Kubernetes 기초 - 최용호용호 최
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample applicationAntoine Rey
 
Jetpack Compose.pptx
Jetpack Compose.pptxJetpack Compose.pptx
Jetpack Compose.pptxGDSCVJTI
 
stupid-simple-kubernetes-final.pdf
stupid-simple-kubernetes-final.pdfstupid-simple-kubernetes-final.pdf
stupid-simple-kubernetes-final.pdfDaniloQueirozMota
 
Jetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UIJetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UIGilang Ramadhan
 
LDAP Injection & Blind LDAP Injection
LDAP Injection & Blind LDAP InjectionLDAP Injection & Blind LDAP Injection
LDAP Injection & Blind LDAP InjectionChema Alonso
 
Shipping Data from Postgres to Clickhouse, by Murat Kabilov, Adjust
Shipping Data from Postgres to Clickhouse, by Murat Kabilov, AdjustShipping Data from Postgres to Clickhouse, by Murat Kabilov, Adjust
Shipping Data from Postgres to Clickhouse, by Murat Kabilov, AdjustAltinity Ltd
 
Kubernetes Workshop
Kubernetes WorkshopKubernetes Workshop
Kubernetes Workshoploodse
 
Spring cloud on kubernetes
Spring cloud on kubernetesSpring cloud on kubernetes
Spring cloud on kubernetesSangSun Park
 
Domain-Driven-Design 정복기 2탄
Domain-Driven-Design 정복기 2탄Domain-Driven-Design 정복기 2탄
Domain-Driven-Design 정복기 2탄Suhyeon Jo
 
Formation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataFormation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataLhouceine OUHAMZA
 
Kafka at half the price with JBOD setup
Kafka at half the price with JBOD setupKafka at half the price with JBOD setup
Kafka at half the price with JBOD setupDong Lin
 
Podman Overview and internals.pdf
Podman Overview and internals.pdfPodman Overview and internals.pdf
Podman Overview and internals.pdfSaim Safder
 

Tendances (20)

Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...
Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...
Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...
 
Docker & Kubernetes 기초 - 최용호
Docker & Kubernetes 기초 - 최용호Docker & Kubernetes 기초 - 최용호
Docker & Kubernetes 기초 - 최용호
 
Dockerfile
Dockerfile Dockerfile
Dockerfile
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
 
Jetpack Compose.pptx
Jetpack Compose.pptxJetpack Compose.pptx
Jetpack Compose.pptx
 
KrakenD API Gateway
KrakenD API GatewayKrakenD API Gateway
KrakenD API Gateway
 
Fast api
Fast apiFast api
Fast api
 
stupid-simple-kubernetes-final.pdf
stupid-simple-kubernetes-final.pdfstupid-simple-kubernetes-final.pdf
stupid-simple-kubernetes-final.pdf
 
Jetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UIJetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UI
 
LDAP Injection & Blind LDAP Injection
LDAP Injection & Blind LDAP InjectionLDAP Injection & Blind LDAP Injection
LDAP Injection & Blind LDAP Injection
 
Shipping Data from Postgres to Clickhouse, by Murat Kabilov, Adjust
Shipping Data from Postgres to Clickhouse, by Murat Kabilov, AdjustShipping Data from Postgres to Clickhouse, by Murat Kabilov, Adjust
Shipping Data from Postgres to Clickhouse, by Murat Kabilov, Adjust
 
Docker, LinuX Container
Docker, LinuX ContainerDocker, LinuX Container
Docker, LinuX Container
 
Kubernetes Workshop
Kubernetes WorkshopKubernetes Workshop
Kubernetes Workshop
 
React JS
React JSReact JS
React JS
 
Spring cloud on kubernetes
Spring cloud on kubernetesSpring cloud on kubernetes
Spring cloud on kubernetes
 
Domain-Driven-Design 정복기 2탄
Domain-Driven-Design 정복기 2탄Domain-Driven-Design 정복기 2탄
Domain-Driven-Design 정복기 2탄
 
Formation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataFormation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-data
 
Asp.net caching
Asp.net cachingAsp.net caching
Asp.net caching
 
Kafka at half the price with JBOD setup
Kafka at half the price with JBOD setupKafka at half the price with JBOD setup
Kafka at half the price with JBOD setup
 
Podman Overview and internals.pdf
Podman Overview and internals.pdfPodman Overview and internals.pdf
Podman Overview and internals.pdf
 

En vedette

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 wholeIlan Godik
 
λ | Lenses
λ | Lensesλ | Lenses
λ | LensesOpen-IT
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functionaldjspiewak
 
こわくない型クラス
こわくない型クラスこわくない型クラス
こわくない型クラスKota Mizushima
 
Scalaで型クラス入門
Scalaで型クラス入門Scalaで型クラス入門
Scalaで型クラス入門Makoto Fukuhara
 
Grokking Monads in Scala
Grokking Monads in ScalaGrokking Monads in Scala
Grokking Monads in ScalaTim Dalton
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless Jared Roesch
 

En vedette (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
 

Similaire à Scala lens: An introduction

Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San FranciscoMartin Odersky
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
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...7mind
 
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.jsKnoldus Inc.
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaScala Italy
 
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 RecapDave Orme
 
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 ScalaMarakana Inc.
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversBrian Gesiak
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async LibraryKnoldus Inc.
 
Angular JS in 2017
Angular JS in 2017Angular JS in 2017
Angular JS in 2017Ayush Sharma
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS MeetupLINAGORA
 
Jaoo Michael Neale 09
Jaoo Michael Neale 09Jaoo Michael Neale 09
Jaoo Michael Neale 09Michael Neale
 
RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteDr Nic Williams
 

Similaire à 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
 

Plus de Knoldus Inc.

Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
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 PresentationKnoldus Inc.
 
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 APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxKnoldus Inc.
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinKnoldus Inc.
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks PresentationKnoldus Inc.
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Knoldus Inc.
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxKnoldus Inc.
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance TestingKnoldus Inc.
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxKnoldus Inc.
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationKnoldus Inc.
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.Knoldus Inc.
 

Plus de Knoldus Inc. (20)

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
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptx
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and Kotlin
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks Presentation
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptx
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance Testing
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptx
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower Presentation
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.
 

Dernier

BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxryandux83rd
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...Nguyen Thanh Tu Collection
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 

Dernier (20)

BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptx
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Chi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical VariableChi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical Variable
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 

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

Notes de l'éditeur

  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