[swift-evolution] [Preemptive Proposal] Operator for Lenses

Michael Henson mikehenson at gmail.com
Thu Jan 14 18:10:17 CST 2016


There hasn't been a major Lens thread on the list so far, but I'm intrigued
by the idea and was tinkering with a related proposal until I stumbled
across Brandon William's "Lenses in Swift" video and discovered that Lenses
cover everything I wanted to do and more.

The one thing that stuck with me, though, is the question of syntax. If
Lenses are to be a native part of the Swift language, how would one declare
them?

We've currently got not-so-secret methods at the type level of Structs and
Classes for every member function:

class Example {
    func action() {}
}

let example = Example()
example.action // () -> Void
Example.action // (Example) -> Void

That looks a lot like a Lens on the member function, though if I understand
correctly the current plan is for those to go away in a future version.

We also have to deal with Type-level members and functions:

class Example {
   static action() {}
   static name: String
}

Example.action() // () -> Void
Example.name // String

So, using a dot-operator as the way to get a Lens could be problematic due
to name collisions.

The Proposal:

Use the '#' character in place of the dot operator to retrieve a Lens for a
Type/member pair:

Example#action() // (Example) -> Void
Example#name    // Lens<Example,String>, autogenerated to work on the
'name' member

Member function names should be fully-specified with the mechanism from
Doug Gregor's method naming proposal.

Some notes:
* A specific operator stands out and is easier to scan for as a code reader.
* The octothorpe seems to be available in Swift.
* It also has a current meaning in a technology familiar to most everyone -
the Document Fragment in HTML - which could make the idea easier to explain
to newcomers, by analogy.

What about Lenses on Type-level members? My first thought is that we don't
have to support that because they're more like namespaced globals rather
than parts of a data type. They can always be referenced directly. That
might be a vacuous observation to people more familiar with the Lens
concept, but I noted it for completeness.

Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160114/8e68b2af/attachment.html>


More information about the swift-evolution mailing list