SlideShare a Scribd company logo
Zippers
David Overton
1 August 2013
Table of Contents
1 Motivation
2 List Zipper
3 Tree Zippers
4 Algebraic Data Types
5 Type Differentiation
6 Conclusion
Motivation
Navigating around in and updating mutable data structures is easy:
• Keep a pointer to your current location in the data structure;
• Update the pointer to move around the data structure;
• Modify the data structure using destructive update via the pointer.
Example (C Array)
char my_array[1024];
char *p = my_array;
// Move right
p++;
// Move left
p--;
// Update focused element
*p = ’A’;
Motivation
But what is the equivalent for an immutable data structure? I.e. how do we keep track
of a local focus point within a data structure? E.g. XML document tree, text editor
buffer, window manager stack (e.g. XMonad), AVL tree.
For a list we could use an integer to represent the element we are interested in:
type ListFocus a = (Int, [a])
but this requires traversing from the start of the list every time – an O(n) operation.
For more complex types, this is even less practical.
Instead, we can use a data structure called a zipper.
Table of Contents
1 Motivation
2 List Zipper
3 Tree Zippers
4 Algebraic Data Types
5 Type Differentiation
6 Conclusion
List Zipper
-- A list zipper is a pair consisting of the front
-- of the list (reversed) and the rear of the list.
type ListZipper a = ([a], [a])
-- Convert a list to a zipper.
-- Start at the front of the list.
fromList :: [a] → ListZipper a
fromList xs = ([], xs)
List Zipper
-- Move about in the zipper.
right, left :: ListZipper a → ListZipper a
right (xs, y:ys) = (y:xs, ys)
left (x:xs, ys) = (xs, x:ys)
-- Modify the focused element.
modify :: (a → a) → ListZipper a → ListZipper a
modify f (xs, y:ys) = (xs, (f y):ys)
modify _ zs = zs
-- When we are finished, convert back to a list.
toList :: ListZipper a → [a]
toList ([], ys) = ys
toList zs = toList (left zs)
*Main> let z = fromList [’a’, ’b’, ’c’]
*Main> z
("","abc")
a
ctx list
b
c
*Main> right z
("a","bc")
a
ctx list
b
c
*Main> right $ right z
("ba","c")
a
ctx list
b c
*Main> right $ right $ right z
("cba","")
a
ctx list
b
c
List Zipper
Example (XMonad)
XMonad is a tiling window manager for X written in Haskell. The main data structure
for managing workspace and window focus uses nested list zippers.
type StackSet a = ListZipper (Workspace a)
type Workspace a = ListZipper (Window a)
This allows XMonad to keep track of the focused workspace in an ordered list of
workspaces and also keep track of the focused window on each workspace.
(This is a simplification of the actual types used. The zippers that XMonad uses allow
wrapping when you reach the end of the window or workspace list.)
Table of Contents
1 Motivation
2 List Zipper
3 Tree Zippers
4 Algebraic Data Types
5 Type Differentiation
6 Conclusion
Binary Tree
data Tree a
= Empty
| Node (Tree a) a (Tree a)
deriving Show
type Context a = Either (a, Tree a) (a, Tree a)
type TreeZipper a = ([Context a], Tree a)
fromTree :: Tree a → TreeZipper a
fromTree t = ([], t)
right, left, up :: TreeZipper a → TreeZipper a
right (ctx, Node l a r) = (Right (a, l) : ctx, r)
left (ctx, Node l a r) = (Left (a, r) : ctx, l)
Binary Tree
up (Left (a, r) : ctx, l) = (ctx, Node l a r)
up (Right (a, l) : ctx, r) = (ctx, Node l a r)
modify :: (a → a) → TreeZipper a → TreeZipper a
modify f (ctx, Node l a r) = (ctx, Node l (f a) r)
modify f z = z
toTree :: TreeZipper a → Tree a
toTree ([], t) = t
toTree z = toTree (up z)
*Main> let t = Node
(Node
(Node Empty ’d’ Empty)
’b’
(Node Empty ’e’ Empty))
’a’
(Node
(Node Empty ’f’ Empty)
’c’
(Node Empty ’g’ Empty))
*Main> fromTree t
a
cb
ed gf
ctx tree
*Main> right $ fromTree t
( [Right (’a’,
Node
(Node Empty ’d’ Empty)
’b’
(Node Empty ’e’ Empty))],
Node
(Node Empty ’f’ Empty)
’c’
(Node Empty ’g’ Empty) )
Right
a c
b
ed
gf
ctx tree
*Main> left $ right $ fromTree t
( [ Left (’c’, Node Empty ’g’ Empty),
Right (’a’,
Node
(Node Empty ’d’ Empty)
’b’
(Node Empty ’e’ Empty))],
Node Empty ’f’ Empty )
Right
Left
a
c
b
ed
g
f
ctx tree
Tree Zippers
Example (XML)
• XPath navigation around an XML document is basically a zipper – you have a
current context and methods to navigate to neighbouring nodes.
• One implementation of this in Haskell is the rose tree zipper from HXT.
data NTree a = NTree a [NTree a] -- A rose tree
data NTCrumb = NTC [NTree a] a [NTree a] -- "Breadcrumb" for context
-- The zipper itself
data NTZipper a = NTZ { ntree :: NTree a, context :: [NTCrumb a] }
-- And using it to represent XML
type XmlTree = NTree XNode
type XmlNavTree = NTZipper XNode
data XNode = XText String | XTag QName [XmlTree] | XAttr QName | · · ·
Table of Contents
1 Motivation
2 List Zipper
3 Tree Zippers
4 Algebraic Data Types
5 Type Differentiation
6 Conclusion
Algebraic Data Types
Why are the types in languages such as Haskell sometimes referred to as Algebraic
Data Types? One way to see the relationship to algebra is to convert the types to
algebraic expressions which represent the number of values that a type has.
data Void ⇔ 0 The empty type
data () = () ⇔ 1 The unit type
data Either a b = Left a | Right b ⇔ a + b A sum type
type Pair a b = (a, b) ⇔ a.b A product type
Technically, Haskell types form an algebraic structure called a semiring.
Some more examples:
data Bool = False | True ⇔ 2
data Maybe a = Nothing | Just a ⇔ 1 + a
type Func a b = a -> b ⇔ ba An exponential type
Int ⇔ 232 or 264 (implementation dependent)
Algebraic Laws
The usual algebraic laws (for semirings) hold, up to type “equivalence”:
0 + a = a ⇔ Either Void a ∼= a
a + b = b + a ⇔ Either a b ∼= Either b a
0.a = 0 ⇔ (Void, a) ∼= Void
1.a = a ⇔ ((), a) ∼= a
a.b = b.a ⇔ (a, b) ∼= (b, a)
a.(b + c) = a.b + a.c ⇔ (a, Either b c) ∼= Either (a,b) (a,c)
(cb)a = cb.a ⇔ a -> b -> c ∼= (a, b) -> c
a2 = a.a ⇔ Bool -> a ∼= (a, a)
Algebra of the List Type
data List a = Nil | Cons a (List a)
L(a) = 1 + a.L(a)
= 1 + a.(1 + a.L(a))
= 1 + a + a2(1 + a.L(a))
= 1 + a + a2 + a3 + a4 + · · ·
So a list has either 0 elements or 1 element or 2 elements or . . . (which we already
knew!).
Alternatively, solving for L(a):
L(a) − a.L(a) = 1
(1 − a).L(a) = 1
L(a) =
1
1 − a
It doesn’t seem to make much sense to do subtraction or division on types. But look
at the Taylor series expansion:
1
1 − a
= 1 + a + a2 + a3 + a4 + · · ·
Algebra of Tree Types
data Tree a = Empty | Node (Tree a) a (Tree a)
T(a) = 1 + a.T(a)2
a.T(a)2 − T(a) + 1 = 0
T(a) =
1 −
√
1 − 4.a
2.a
= 1 + a + 2a2 + 5a3 + 14a4 + · · ·
via the quadratic formula and Taylor series expansion. But now we are taking square
roots of types!
Table of Contents
1 Motivation
2 List Zipper
3 Tree Zippers
4 Algebraic Data Types
5 Type Differentiation
6 Conclusion
One-Hole Contexts
Definition
The one-hole context of a parameterised type T(a) is the type of data structures you
get if you remove one distinguished element of type a from a data structure of type
T(a) and somehow mark the hole where the element came from.
Example
type Triple a = (a, a, a)
The one-hole contexts are ( , a, a), (a, , a), and (a, a, ). A type that could
represent this is
data TripleOhc a = Left a a | Mid a a | Right a a
One-Hole Contexts
Look at the algebraic types:
type Triple a = (a, a, a) ⇔ a3
type TripleOhc a = Left a a | Mid a a | Right a a ⇔ 3a2
Notice that
3a2
=
d
da
a3
In fact, this this relationship holds for any parameterised type T(a).
Observation
The type of the one-hole context of any parameterized type T(a) is the derivative type
d
da
T(a) or ∂aT(a)
Zippers from One-Hole Contexts
Observation
For any parameterized type T(a), the type a.∂aT(a) is a zipper for type T(a).
Example
The type
type TripleZipper a = (a, TripleOhc a)
is a zipper for the type Triple a.
TripleZipper(a) = a.3a2
= 3a3
= 3.Triple(a)
But what about some more interesting types . . . ?
List Zipper
L(a) =
1
1 − a
∂aL(a) =
1
(1 − a)2
= L(a)2
ZL(a) = a.∂aL(a) = a.L(a)2
type ListZipper a = (a, [a], [a])
This is slightly different from our original list zipper type ([a], [a]). The
distinguished element is now pulled out of the second list and made explicit. This also
means that the zipper can’t be empty. However, this is still a list zipper and we derived
it using the differential calculus!
Tree Zipper
T(a) = 1 + a.T(a)2
∂aT(a) = T(a)2 + 2a.T(a).∂aT(a)
∂aT(a) =
T(a)2
1 − 2a.T(a)
= T(a)2.L(2a.T(a))
ZT (a) = a.∂aT(a)
= a.T(a)2.L(2a.T(a))
type Context a = Either (a, Tree a) (a, Tree a)
type TreeZipper a = (a, Tree a, Tree a, [Context a])
Table of Contents
1 Motivation
2 List Zipper
3 Tree Zippers
4 Algebraic Data Types
5 Type Differentiation
6 Conclusion
Conclusion
• Zippers are a useful way of navigating and manipulating mutable data structures
in real-world functional programs.
• Algebraic data types really are algebraic.
• Differentiation of types can lead to automatic derivation of zippers.
• Nobody really knows why this works yet — active research.

More Related Content

What's hot

Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithms
samairaakram
 
Shell sort
Shell sortShell sort
recursion tree method.pdf
recursion tree method.pdfrecursion tree method.pdf
recursion tree method.pdf
MalikShazen
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
Knoldus Inc.
 
Taking your side effects aside
Taking your side effects asideTaking your side effects aside
Taking your side effects aside
💡 Tomasz Kogut
 
Gentle Introduction to Scala
Gentle Introduction to ScalaGentle Introduction to Scala
Gentle Introduction to Scala
Fangda Wang
 
Shell sorting
Shell sortingShell sorting
Shell sorting
TUC
 
Learn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & MethodsLearn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & Methods
Eng Teong Cheah
 
Hashing in datastructure
Hashing in datastructureHashing in datastructure
Hashing in datastructure
rajshreemuthiah
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
fawzmasood
 
Greedy Algorihm
Greedy AlgorihmGreedy Algorihm
Greedy Algorihm
Muhammad Amjad Rana
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in PythonBen James
 
Heap sort
Heap sort Heap sort
Chapter 1 Data structure.pptx
Chapter 1 Data structure.pptxChapter 1 Data structure.pptx
Chapter 1 Data structure.pptx
wondmhunegn
 
Shell sort in Data Structure Using C
Shell sort in Data Structure Using CShell sort in Data Structure Using C
Shell sort in Data Structure Using CAshish Gaurkhede
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
Abdelrahman Saleh
 
Queues
QueuesQueues
Queues
Hareem Aslam
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
Aabha Tiwari
 

What's hot (20)

Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithms
 
Shell sort
Shell sortShell sort
Shell sort
 
recursion tree method.pdf
recursion tree method.pdfrecursion tree method.pdf
recursion tree method.pdf
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
Taking your side effects aside
Taking your side effects asideTaking your side effects aside
Taking your side effects aside
 
Gentle Introduction to Scala
Gentle Introduction to ScalaGentle Introduction to Scala
Gentle Introduction to Scala
 
Shell sorting
Shell sortingShell sorting
Shell sorting
 
Learn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & MethodsLearn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & Methods
 
Hashing in datastructure
Hashing in datastructureHashing in datastructure
Hashing in datastructure
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
 
Greedy Algorihm
Greedy AlgorihmGreedy Algorihm
Greedy Algorihm
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
 
Heap sort
Heap sort Heap sort
Heap sort
 
Chapter 1 Data structure.pptx
Chapter 1 Data structure.pptxChapter 1 Data structure.pptx
Chapter 1 Data structure.pptx
 
Lec12
Lec12Lec12
Lec12
 
Shell sort in Data Structure Using C
Shell sort in Data Structure Using CShell sort in Data Structure Using C
Shell sort in Data Structure Using C
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Queues
QueuesQueues
Queues
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 

Viewers also liked

ASSQC on snap fasteners and buttons
ASSQC on snap fasteners and buttonsASSQC on snap fasteners and buttons
ASSQC on snap fasteners and buttons
Shreeti Mishra
 
Basic stitches
Basic stitchesBasic stitches
Basic stitches
Jesus Obenita Jr.
 
Different types of button are used in garments
Different types of button are used in garmentsDifferent types of button are used in garments
Different types of button are used in garments
Hindustan University
 
Basic hand stitches
Basic hand stitchesBasic hand stitches
Basic hand stitches
ampolito
 
K to 12 Tailoring/Dressmaking - Basic Hand Stitches
K to 12 Tailoring/Dressmaking - Basic Hand Stitches K to 12 Tailoring/Dressmaking - Basic Hand Stitches
K to 12 Tailoring/Dressmaking - Basic Hand Stitches Rona De la Rama
 
Basic Hand Stitches
Basic Hand StitchesBasic Hand Stitches
Basic Hand Stitches
jerebelle dulla
 
Textile & garments (1)- Trims & accessories of garments
Textile &  garments (1)- Trims & accessories of garmentsTextile &  garments (1)- Trims & accessories of garments
Textile & garments (1)- Trims & accessories of garments
Rabiul robi
 
Trims & Accessories
Trims & AccessoriesTrims & Accessories
Trims & Accessories
Likhon Ahmed
 

Viewers also liked (10)

ASSQC on snap fasteners and buttons
ASSQC on snap fasteners and buttonsASSQC on snap fasteners and buttons
ASSQC on snap fasteners and buttons
 
Zipper
ZipperZipper
Zipper
 
Basic stitches
Basic stitchesBasic stitches
Basic stitches
 
Different types of button are used in garments
Different types of button are used in garmentsDifferent types of button are used in garments
Different types of button are used in garments
 
Basic hand stitches
Basic hand stitchesBasic hand stitches
Basic hand stitches
 
K to 12 Tailoring/Dressmaking - Basic Hand Stitches
K to 12 Tailoring/Dressmaking - Basic Hand Stitches K to 12 Tailoring/Dressmaking - Basic Hand Stitches
K to 12 Tailoring/Dressmaking - Basic Hand Stitches
 
Basic Hand Stitches
Basic Hand StitchesBasic Hand Stitches
Basic Hand Stitches
 
The Zipper
The ZipperThe Zipper
The Zipper
 
Textile & garments (1)- Trims & accessories of garments
Textile &  garments (1)- Trims & accessories of garmentsTextile &  garments (1)- Trims & accessories of garments
Textile & garments (1)- Trims & accessories of garments
 
Trims & Accessories
Trims & AccessoriesTrims & Accessories
Trims & Accessories
 

Similar to Zippers

Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
Raymond Tay
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
Hang Zhao
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsVasil Remeniuk
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
Kirill Kozlov
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
Kirill Kozlov
 
Array
ArrayArray
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scalaMeetu Maltiar
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform ResearchVasil Remeniuk
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
Knoldus Inc.
 
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
PROIDEA
 
List,Stacks and Queues.pptx
List,Stacks and Queues.pptxList,Stacks and Queues.pptx
List,Stacks and Queues.pptx
UmatulSaboohSaleem1
 
tidyr.pdf
tidyr.pdftidyr.pdf
tidyr.pdf
Mateus S. Xavier
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
Hang Zhao
 
Your data structures are made of maths!
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!
kenbot
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scaladjspiewak
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Bryan O'Sullivan
 
[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ
[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ
[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ
Provectus
 

Similar to Zippers (20)

Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami Patterns
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
Array
ArrayArray
Array
 
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scala
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
 
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
 
List,Stacks and Queues.pptx
List,Stacks and Queues.pptxList,Stacks and Queues.pptx
List,Stacks and Queues.pptx
 
Q
QQ
Q
 
tidyr.pdf
tidyr.pdftidyr.pdf
tidyr.pdf
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
Your data structures are made of maths!
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6
 
R교육1
R교육1R교육1
R교육1
 
[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ
[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ
[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ
 

Recently uploaded

Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 

Recently uploaded (20)

Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 

Zippers

  • 2. Table of Contents 1 Motivation 2 List Zipper 3 Tree Zippers 4 Algebraic Data Types 5 Type Differentiation 6 Conclusion
  • 3. Motivation Navigating around in and updating mutable data structures is easy: • Keep a pointer to your current location in the data structure; • Update the pointer to move around the data structure; • Modify the data structure using destructive update via the pointer. Example (C Array) char my_array[1024]; char *p = my_array; // Move right p++; // Move left p--; // Update focused element *p = ’A’;
  • 4. Motivation But what is the equivalent for an immutable data structure? I.e. how do we keep track of a local focus point within a data structure? E.g. XML document tree, text editor buffer, window manager stack (e.g. XMonad), AVL tree. For a list we could use an integer to represent the element we are interested in: type ListFocus a = (Int, [a]) but this requires traversing from the start of the list every time – an O(n) operation. For more complex types, this is even less practical. Instead, we can use a data structure called a zipper.
  • 5. Table of Contents 1 Motivation 2 List Zipper 3 Tree Zippers 4 Algebraic Data Types 5 Type Differentiation 6 Conclusion
  • 6. List Zipper -- A list zipper is a pair consisting of the front -- of the list (reversed) and the rear of the list. type ListZipper a = ([a], [a]) -- Convert a list to a zipper. -- Start at the front of the list. fromList :: [a] → ListZipper a fromList xs = ([], xs)
  • 7. List Zipper -- Move about in the zipper. right, left :: ListZipper a → ListZipper a right (xs, y:ys) = (y:xs, ys) left (x:xs, ys) = (xs, x:ys) -- Modify the focused element. modify :: (a → a) → ListZipper a → ListZipper a modify f (xs, y:ys) = (xs, (f y):ys) modify _ zs = zs -- When we are finished, convert back to a list. toList :: ListZipper a → [a] toList ([], ys) = ys toList zs = toList (left zs)
  • 8. *Main> let z = fromList [’a’, ’b’, ’c’] *Main> z ("","abc") a ctx list b c
  • 10. *Main> right $ right z ("ba","c") a ctx list b c
  • 11. *Main> right $ right $ right z ("cba","") a ctx list b c
  • 12. List Zipper Example (XMonad) XMonad is a tiling window manager for X written in Haskell. The main data structure for managing workspace and window focus uses nested list zippers. type StackSet a = ListZipper (Workspace a) type Workspace a = ListZipper (Window a) This allows XMonad to keep track of the focused workspace in an ordered list of workspaces and also keep track of the focused window on each workspace. (This is a simplification of the actual types used. The zippers that XMonad uses allow wrapping when you reach the end of the window or workspace list.)
  • 13. Table of Contents 1 Motivation 2 List Zipper 3 Tree Zippers 4 Algebraic Data Types 5 Type Differentiation 6 Conclusion
  • 14. Binary Tree data Tree a = Empty | Node (Tree a) a (Tree a) deriving Show type Context a = Either (a, Tree a) (a, Tree a) type TreeZipper a = ([Context a], Tree a) fromTree :: Tree a → TreeZipper a fromTree t = ([], t) right, left, up :: TreeZipper a → TreeZipper a right (ctx, Node l a r) = (Right (a, l) : ctx, r) left (ctx, Node l a r) = (Left (a, r) : ctx, l)
  • 15. Binary Tree up (Left (a, r) : ctx, l) = (ctx, Node l a r) up (Right (a, l) : ctx, r) = (ctx, Node l a r) modify :: (a → a) → TreeZipper a → TreeZipper a modify f (ctx, Node l a r) = (ctx, Node l (f a) r) modify f z = z toTree :: TreeZipper a → Tree a toTree ([], t) = t toTree z = toTree (up z)
  • 16. *Main> let t = Node (Node (Node Empty ’d’ Empty) ’b’ (Node Empty ’e’ Empty)) ’a’ (Node (Node Empty ’f’ Empty) ’c’ (Node Empty ’g’ Empty)) *Main> fromTree t a cb ed gf ctx tree
  • 17. *Main> right $ fromTree t ( [Right (’a’, Node (Node Empty ’d’ Empty) ’b’ (Node Empty ’e’ Empty))], Node (Node Empty ’f’ Empty) ’c’ (Node Empty ’g’ Empty) ) Right a c b ed gf ctx tree
  • 18. *Main> left $ right $ fromTree t ( [ Left (’c’, Node Empty ’g’ Empty), Right (’a’, Node (Node Empty ’d’ Empty) ’b’ (Node Empty ’e’ Empty))], Node Empty ’f’ Empty ) Right Left a c b ed g f ctx tree
  • 19. Tree Zippers Example (XML) • XPath navigation around an XML document is basically a zipper – you have a current context and methods to navigate to neighbouring nodes. • One implementation of this in Haskell is the rose tree zipper from HXT. data NTree a = NTree a [NTree a] -- A rose tree data NTCrumb = NTC [NTree a] a [NTree a] -- "Breadcrumb" for context -- The zipper itself data NTZipper a = NTZ { ntree :: NTree a, context :: [NTCrumb a] } -- And using it to represent XML type XmlTree = NTree XNode type XmlNavTree = NTZipper XNode data XNode = XText String | XTag QName [XmlTree] | XAttr QName | · · ·
  • 20. Table of Contents 1 Motivation 2 List Zipper 3 Tree Zippers 4 Algebraic Data Types 5 Type Differentiation 6 Conclusion
  • 21. Algebraic Data Types Why are the types in languages such as Haskell sometimes referred to as Algebraic Data Types? One way to see the relationship to algebra is to convert the types to algebraic expressions which represent the number of values that a type has. data Void ⇔ 0 The empty type data () = () ⇔ 1 The unit type data Either a b = Left a | Right b ⇔ a + b A sum type type Pair a b = (a, b) ⇔ a.b A product type Technically, Haskell types form an algebraic structure called a semiring. Some more examples: data Bool = False | True ⇔ 2 data Maybe a = Nothing | Just a ⇔ 1 + a type Func a b = a -> b ⇔ ba An exponential type Int ⇔ 232 or 264 (implementation dependent)
  • 22. Algebraic Laws The usual algebraic laws (for semirings) hold, up to type “equivalence”: 0 + a = a ⇔ Either Void a ∼= a a + b = b + a ⇔ Either a b ∼= Either b a 0.a = 0 ⇔ (Void, a) ∼= Void 1.a = a ⇔ ((), a) ∼= a a.b = b.a ⇔ (a, b) ∼= (b, a) a.(b + c) = a.b + a.c ⇔ (a, Either b c) ∼= Either (a,b) (a,c) (cb)a = cb.a ⇔ a -> b -> c ∼= (a, b) -> c a2 = a.a ⇔ Bool -> a ∼= (a, a)
  • 23. Algebra of the List Type data List a = Nil | Cons a (List a) L(a) = 1 + a.L(a) = 1 + a.(1 + a.L(a)) = 1 + a + a2(1 + a.L(a)) = 1 + a + a2 + a3 + a4 + · · · So a list has either 0 elements or 1 element or 2 elements or . . . (which we already knew!). Alternatively, solving for L(a): L(a) − a.L(a) = 1 (1 − a).L(a) = 1 L(a) = 1 1 − a It doesn’t seem to make much sense to do subtraction or division on types. But look at the Taylor series expansion: 1 1 − a = 1 + a + a2 + a3 + a4 + · · ·
  • 24. Algebra of Tree Types data Tree a = Empty | Node (Tree a) a (Tree a) T(a) = 1 + a.T(a)2 a.T(a)2 − T(a) + 1 = 0 T(a) = 1 − √ 1 − 4.a 2.a = 1 + a + 2a2 + 5a3 + 14a4 + · · · via the quadratic formula and Taylor series expansion. But now we are taking square roots of types!
  • 25. Table of Contents 1 Motivation 2 List Zipper 3 Tree Zippers 4 Algebraic Data Types 5 Type Differentiation 6 Conclusion
  • 26. One-Hole Contexts Definition The one-hole context of a parameterised type T(a) is the type of data structures you get if you remove one distinguished element of type a from a data structure of type T(a) and somehow mark the hole where the element came from. Example type Triple a = (a, a, a) The one-hole contexts are ( , a, a), (a, , a), and (a, a, ). A type that could represent this is data TripleOhc a = Left a a | Mid a a | Right a a
  • 27. One-Hole Contexts Look at the algebraic types: type Triple a = (a, a, a) ⇔ a3 type TripleOhc a = Left a a | Mid a a | Right a a ⇔ 3a2 Notice that 3a2 = d da a3 In fact, this this relationship holds for any parameterised type T(a). Observation The type of the one-hole context of any parameterized type T(a) is the derivative type d da T(a) or ∂aT(a)
  • 28. Zippers from One-Hole Contexts Observation For any parameterized type T(a), the type a.∂aT(a) is a zipper for type T(a). Example The type type TripleZipper a = (a, TripleOhc a) is a zipper for the type Triple a. TripleZipper(a) = a.3a2 = 3a3 = 3.Triple(a) But what about some more interesting types . . . ?
  • 29. List Zipper L(a) = 1 1 − a ∂aL(a) = 1 (1 − a)2 = L(a)2 ZL(a) = a.∂aL(a) = a.L(a)2 type ListZipper a = (a, [a], [a]) This is slightly different from our original list zipper type ([a], [a]). The distinguished element is now pulled out of the second list and made explicit. This also means that the zipper can’t be empty. However, this is still a list zipper and we derived it using the differential calculus!
  • 30. Tree Zipper T(a) = 1 + a.T(a)2 ∂aT(a) = T(a)2 + 2a.T(a).∂aT(a) ∂aT(a) = T(a)2 1 − 2a.T(a) = T(a)2.L(2a.T(a)) ZT (a) = a.∂aT(a) = a.T(a)2.L(2a.T(a)) type Context a = Either (a, Tree a) (a, Tree a) type TreeZipper a = (a, Tree a, Tree a, [Context a])
  • 31. Table of Contents 1 Motivation 2 List Zipper 3 Tree Zippers 4 Algebraic Data Types 5 Type Differentiation 6 Conclusion
  • 32. Conclusion • Zippers are a useful way of navigating and manipulating mutable data structures in real-world functional programs. • Algebraic data types really are algebraic. • Differentiation of types can lead to automatic derivation of zippers. • Nobody really knows why this works yet — active research.