Focussing Haskell on Perl 6
On the bus ride out to Charleroi I caught a stray brainwave about how to properly notate at least some of Haskell's Lens library, so I wrote up some notes on it. This is going to be slightly spooky, but not much more than the previously-existing ability to bind one data structure to another.
I do want to finish up the Scheme work, if only to prove the crowd on Perlmonks wrong, first though.
The 'lens' library is essentially a metaphor for focussing in on your data, in roughly the following sense:
my $lens = Optical::Bench::BeamSplitter.new;
$a =< $lens >= $b; # Think of $a "passing through" $lens into $b.
$a = 'foo bar';
is-deeply $b, [ 'foo', 'bar' ];
$b.[1] = 'moo';
is $a, 'foo moo';
Lenses can be chained:
my $lens2 = Optical::Bench::BeamSplitter.new('-');
$a =< $lens >=< $lens2 >= $b;
$a = 'foo-bar baz-qux';
is-deeply $b, [ [ 'foo', 'bar' ], [ 'baz', 'qux' ] ];
If that behavior is a little too magical, use the '<<' and/or '>>', and then the changes only go in one direction, or none at all (but they'll still happen on binding.)
$a << $lens >= $b;
$a = 'foo bar'; is-deeply $b, [ 'foo', 'bar' ]; # ok 1
$b.[0] = 'moo'; is-deeply $b, [ 'moo', 'bar' ]; is $a, 'foo bar'; # ok 2, ok 3
If you're having trouble coming up with a use for this, envision database work, where you have a transform (like, say, converting timestamps) you need to do on the way in and out of the database:
my $lens = O::B::mySQL.new('Mmm dd, yyy');
$created-date =< $lens >= $created-date-mySQL;
is $created-date, 'Feb 3, 2016';
is $created-date-mySQL, '2016-02-03T09:50+02:00';
Put this anywhere in your method, and you can rest assured that the mySQL date will be formatted correctly when it gets saved. With sufficient black magic, it might even work like:
$post.<created_date> =< O::B::mySQL::Date.new >= $params.<created_date>;
so you could drop that into your Dancer'ish Controller, or maybe even directly in your database Model, once there's an ORM thing for Perl 6.
I don't know if this library is in the true spirit of the Haskell original, but it feels close. The Haskell library is all about treating Lenses as data types and composing those into different lenses. It might be worth investigating treating Lenses as roles on actual data types, but I'm not sure how the application semantics would work.
I like the concept, but can the syntax be made to look more like the binding operator and less like a comparison? eg
I don't see why not. I was just after the visual metaphor of light rays coming through a lens, but :: seem less confusing. The module itself is on hiatus while I get a few other things done, but that's a good idea.