Unlock This Episode
Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.
Introduction
Today let’s talk about setters! So, the problem is that in our applications we often come across complicated, deeply nested data structures, and we want to be able to modify parts of those structures while keeping everything else fixed. Further, we wanna be able to do it a simple, clean, composable way, where “composable” means that if we have two ways of modify parts of a structure, I should be able to combine them into one thing that modifies both of those parts at the same time.
Subscribe to Point-Free
Access this episode, plus all past and future episodes when you become a subscriber.
Already a subscriber? Log in
Exercises
As we saw with free
map
onArray
, define freemap
onOptional
and use it to compose setters that traverse into an optional field.Take a
struct
, e.g.:struct User { let name: String }
Write a setter for its property. Take (or add) another property, and add a setter for it. What are some potential issues with building these setters?
Take a
struct
with a nestedstruct
, e.g.:struct Location { let name: String } struct User { let location: Location }
Write a setter for
userLocationName
. Now write setters foruserLocation
andlocationName
. How do these setters compose?Do
first
andsecond
work with tuples of three or more values? Can we writefirst
,second
,third
, andnth
for tuples of n values?Write a setter for a dictionary that traverses into a key to set a value.
Write a setter for a dictionary that traverses into a key to set a value if and only if that value already exists.
What is the difference between a function of the form
((A) -> B) -> (C) -> (D)
and one of the form(A) -> (B) -> (C) -> D
?
References
Composable Setters
Stephen Celis • Saturday Sep 30, 2017Stephen spoke about functional setters at the Functional Swift Conference if you’re looking for more material on the topic to reinforce the ideas.
Semantic editor combinators
Conal Elliott • Monday Nov 24, 2008Conal Elliott describes the setter composition we explored in this episode from first principles, using
Haskell. In Haskell, the backwards composition operator <<<
is written simply as a dot .
, which means
that g . f
is the composition of two functions where you apply f
first and then g
. This means if had
a nested value of type ([(A, B)], C)
and wanted to create a setter that transform the B
part, you would
simply write it as first.map.second
, and that looks eerily similar to how you would field access in
the OOP style!