239 points · by pavel_lishin · 14y ago · 154 comments
Mathematicians call it conjugation, and it can be usefully thought of as a temporary change of coordinates or change in vantage point. Problems often become simpler, even trivial, when working in the right coordinates.
In practical programming, it is commonplace that the "inverse" that occurs in conjugation idioms is a genuine right-inverse but only partially a left-inverse. This is true for his example of squares and square roots. For another instance, consider
reverseWords = unwords . reverse . words
The composition words . unwords :: [String] -> [String] is the identity, but unwords . words :: String -> String is the identity only for strings whose words are separated by a single space rather than multiple spaces, tabs, etc. This property can actually be put to good use: normalizeWhitespace = unwords . words
If you like, you can think of unwords . words as an orthogonal projection onto the subspace of strings on which unwords is a genuine left-inverse of words (cf. Moore-Penrose pseudoinverses).That's cool and all, but the effect on reverseWords is that it normalizes interword whitespace in the process of reversing words, whether you like it or not.
Incidentally, it's not too hard to abstract out this pattern with invertible functions:
data Invertible a b = Invertible (a -> b) (b -> a)
invertible = Invertible
apply (Invertible f f') = f
unapply (Invertible f f') = f'
inverse (Invertible f f') = Invertible f' f
compose (Invertible f f') (Invertible g g') = Invertible (f . g) (g' . f')
conjugate i f = unapply i . f . apply i
on = flip conjugate
Now you'd have to set up invertibles for all the usual foo/unfoo pairs of functions. Assume that has been done. Our example only needs words/unwords: import Data.String as S
words = invertible S.words S.unwords
With those preliminaries out of the way, you can then reimplement reverseWords very neatly: reverseWords = reverse `on` words
In fact, it's now so concise and self-explanatory that you hardly need the named definition anymore and can just refer to reverse `on` words directly.fwiw, the haskell bracket docs contain "captures a common allocate, compute, deallocate idiom in which the deallocation step must occur even in the case of an error during computation. This is similar to try-catch-finally in Java. "
http://stlab.adobe.com/wiki/images/2/20/2008_07_25_google.pd...
page 18, 38
this was hosted at googletechtalks http://www.youtube.com/watch?v=4moyKUHApq4 (240p)
At best, you have situations where the flawed reversal is acceptable - the Ruby File::open("file"){} example, or the J example for computing magnitude. close(open("file")) isn't exactly as if nothing had happened.
sqrt(a2) ?= a // only if a >= 0
But, consider parsing and templating: Could you template back exactly the input that you parsed to get an internal representation? Only if every character of input is unambiguous and significant - in other words, almost never.
It's even more like a reflector in a https://en.wikipedia.org/wiki/Reflective_subcategory.
(To make this analogy precise, you'd have to have some category structure where single-space is initial among all whitespace strings. Which is certainly possible; you just have to persuade yourself that that's a natural thing to do.)
Prelude> let xs = [" a"] in xs == (words . unwords) xs
False identity = Invertible id idinstead of
f = open "test.txt"
print f.read
f.close
You can write open "text.txt" do |f|
print f.read
end
The file is automatically closed at the end of the block, and it also handles exceptions and so on. I find it also lines up better semantically with how I think about opening handles to things.I believe Python also added something similar via the 'with' syntax. Not sure about other languages.
with open("text.txt") as inf:
print(inf.read())
User defined classes that implement special methods __enter__() and __exit__() can be used as context managers. More info: http://www.python.org/dev/peps/pep-0343/For just file output/input Scheme has the "with-output-to-file" and "with-input-from-file" macros which redirect output and input to a given file. I vaguely remember Common Lisp having a similar thing, but I can't remember the name off hand.
http://www.lispworks.com/documentation/HyperSpec/Body/m_w_op...
for line in open("name.txt"):
print line # Or do something else with it.def in_context(*args) setup_context yield if block_given? ensure teardown_context end
I guess you could build a special class, but why?
IIRC:
{
ifstream file("text.txt");
copy(istream_iterator<string>(file), istream_iterator<string>(),
ostream_iterator<string>(cout, "\n"));
}//file automatically closed here
and class ThingWithFile {
ifstream file;
public:
ThingWithFile(const char *filename) : file(filename) {}
};
void func() {
ThingWithFile thing("file.name"); //file is opened
} //file is closedWhen an object goes out of scope, the destructor should run immediately; then, when the garbage collector wants to actually deallocate destroyed objects, it can go right ahead. No idiocy like in C# with “using” blocks.
All the garbage collector does is comes through later and deallocates the memory it consumed.
So, in case of C++, object is destroyed when goes out of scope, but the physical act of deallocation may be deferred by the standard library as whatever 'smart memory manager' wishes.
a = new A(); b = new B(); a.b = b; b.a = a;
Whichever you destroy first, the other destructor will have a reference to an unconstructed object.
Objects in the stack are easy to use, logical, and orders of magnitude faster to instantiate than objects in the heap!
(when the underlying runtime uses malloc)
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}Ruby has similar concept when you open a file and pass in a block to operate on the File object.
I'm pretty sure the author is just excited about the language and failed to recognize that this pattern is everywhere in different programming languages.
with_under do_something() as f:
...
translated to f = do_something()
...
f.undo_something()
With do_something automatically matched to undo_something. new FileEx (SOME_PATH, () => ConsoleEx.ReadLine (), () => ConsoleEx.CurrentLine != "QUIT").WriteAll ();
is equivalent to using (var file = new File(SOME_PATH))
{
string line = null;
try
{
while((line = Console.ReadLine) != "QUIT")
{
file.WriteLine(line);
}
}
catch (Exception ex)
{
throw;
}
finally
{
sw.Close();
}
} System.IO.File.AppendAllText(path, "This is some text in the file.");
Also, why are you writing text to binary file instead of just writing the text as a text file?String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } }
Anything that implements the AutoCloseable interface gets this behavior for free.
{
open my $fh, '<', "text.txt";
print scalar <$fh>;
}
# $fh goes out of scope so file handle is closed sub with_open_file {
my ($filename, $code) = @_;
open my $fh, '<', $filename or die $!;
$code->($_) for <$fh>;
close $fh;
}
with_open_file 'text.txt' => sub {
my $f = shift;
print $f;
};
And to add to my original answer it's not just the effects of GC that are handy but also arbitrary scoping. Here is an example of what you can do with nested dynamic scoping: our $rake = "in shed";
sub where_is_rake { say $rake }
where_is_rake; # => in shed
{
# take rake out of shed
local $rake = "rake in hand";
where_is_rake; # => rake in hand
{
# pile up leaves
local $rake = "using rake";
where_is_rake; # = using rake
}
where_is_rake; # => rake in hand
}
where_is_rake; # => in shed using(var db = OpenDbConnection())
{
// read from db, connection closed on next curly.
} f = open("test.txt");
scope(exit) f.close();
print(f.read());
The scope(exit) causes the following statement to be executed at the exit of the scope, regardless of how it leaves (return, goto, fall through, throw, etc.).The advantage over try-finally is the 'finally' statement is associated with the open, rather than some arbitrary distance away.
Which is nowhere near as good, as the closing operation has to be setup explicitly. Go has the same issue with `defer`.
http://www.d-programming-language.org/exception-safe.html
Scope guard has a number of distinct advantages.
It sure makes it easy to be sure you're closing your file handles/database connections/mutexes, though.
with wait_cursor(wxwindow):
... change cursor to hourglass whilst process runs...
I have similar context processors for locking controls or other temporary GUI changesAny time you have an element, y, of a group, the action of pre-composing with any other element, x, and post-composing with x's inverse to get xyx^{-1} is called conjugating, and the result is a called a conjugate of y.
Given the jmp-iness of exception handling in C++, this is the recommended (i.e. the only safe) way to clean up after yourself.
The pattern the article talks about is FAR more general -- it's about all reversible processes, even things that have nothing to do with allocation.
It's the same thing, you can represent the pair (operation, inverse) as a "resource". Python calls it "context management" (and context managers), the means are slightly different, the result's the same.
I agree that OP talks about something of a wider scope though, the language features described in these sub-threads are specialized solutions to precise issues, they're not generalized reversal of arbitrary operations.
In C++ this works amazingly well for objects in the stack (not in the heap, as you need call the destructor yourself).
How about a computer architecture where every instruction has an inverse, and therefore all functions and even programs are invertible? (Quantum computing, for example.)
"Go's defer statement schedules a function call (the deferred function) to be run immediately before the function executing the defer returns. It's an unusual but effective way to deal with situations such as resources that must be released regardless of which path a function takes to return. The canonical examples are unlocking a mutex or closing a file." http://golang.org/doc/effective_go.html#defer
I liked the sum under square better than the read under open example (although the latter may be more relatable). Sum under square squares items, sums them up, and then performs the "inverse-square" operation on the sum. I don't think this is similar to using X or RAII in C++.
http://www.cis.upenn.edu/~bcpierce/papers/lenses-etapsslides...
e.g. read a file, parse it into an AST, modify AST (i.e. rename a variable), unparse the new AST, close the file.
Set origin draw Reset Origin
is
(let ((origin (move 50 50)))
(draw something))
Similar in the Common Lisp object system we use :before, :after and :around methods. (defmethod draw :before () (move 50 50))
(defmethod draw () (draw-something))
(defmethod draw :after () (move -50 -50))Ditto for Moose (in Perl)...
before draw => sub { shift->move( 50, 50 )};
sub draw { shift->draw_something }
after draw => sub { shift->move( -50, -50 )};
Also you can package up these method modifiers into a role which not only can be composed into a class but can also be applied just to an object... {
package DrawRole;
use Moose::Role;
before draw => sub { shift->move( 50, 50 )};
after draw => sub { shift->move( -50, -50 )};
}
my $d = Draw->new;
DrawRole->meta->apply( $d );When you need to wrap up a common block of code, you use a function. This lets you call the same block in a number of different contexts. When you need to fix the context in place and let the block in the middle vary, you write a function that takes another function as a parameter. An example in JavaScript (might be a little off):
var withFile = function (path, action) {
var f;
try {
f = File.open(path);
action(f);
} finally {
File.close(f);
}
};
withFile('foo.txt', function (f) { ... });
This can be generalized (to some extent and depending on language) so you don't need to write the same structures every time: var context = function (prolog, epilog) {
return function (action, ...args) {
var o;
try {
o = prolog.apply(args);
action(o);
} finally {
epilog(o);
}
};
};
var withFile = context(File.open, File.close);
This example uses JavaScript' hypothetical future "rest" parameters, but there are other ways to manage the same goal.(Other comments have mentioned the author conflates context management with applying reversible functions. I've only dealt with one of those things here, but similar techniques apply in solving both problems.)
All the examples of various languages providing this for open files also kind of misses it. The point is not whether a particular language supports this for open files, but whether people recognize the idiom and the language supports doing this yourself wherever it fits. For a pattern this incredibly common it's a point well worth making.
For what it's worth, I think most commonly used languages can implement some form of the context function in my example.
Or macros. Your `context` is called `unwind-protect` in common-lisp.
There's a difference in that `unwind-protect` does not take an "opening form" (which you call `prolog`), and this makes your `context` implementation broken: you're executing the epilog if the prolog blows up, which is not correct as you have an `o` of `undefined` at this point (and your epilog likely awaits some sort of valid resource).
Side-note, your javascript code also looks incorrect, `apply` takes a context (a `this`) as its first parameter, so you're not applying arguments you're taking the `args` array as the `this` of your prolog. You probably wanted to write `prolog.apply(null, args)`.
Few languages have any procedural way to do that.
If Ruby had some way to state "the opposite of opening a file is closing a file" and then use it everywhere, we could do that. The block-syntax open is nearly that, but not quite. You'd need to have no non-block-scope way to use the resource for it to work.
RAII would also give the same benefit, if there were no non-RAII way to declare the resource.
This very significant property is what makes me love RAII. I don't count C#'s using-statement and/or rubys block statement as RAII since it relies on useage patterns. C++'s automatic destruction of graphs of objects also makes it outshine all other methodologies, and the guaranteed destruction is the key here.
Once you're passing a block to a method like this in Ruby, the execution of the cleanup code is just as guaranteed as it is in C++.
You can already do that, just `return unless block_given?`. In principle I don't see why you'd want to non block version anyway but maybe there's some use case where that is valid.
C#'s IDIsposable has this, too.
So do other languages. It's really not that unusual a pattern.
Context managers in Python:
with fly('Seattle'):
see_sights()
Real-world example from Fabric http://fabfile.org: with cd('/to/path'):
do_stuff()However you can use the ``contextlib`` module to make really simple ``contextmanger``'s with the yield statement
e.g.:
from contextlib import contextmanager
@contextmanager
def glcontext():
glBegin()
yield
glEnd()
(This is an example where someone wanted to do OpenGL in python)The first is amply covered by the RAII/unwind-protect etc idioms than most languages do have.
The second is not, as most programming languages don't have the concept. The closest I can think of is the ability to use a predicate in either direction in Prolog (or logical programming in general)
Unfortunately, I don't think he found it particularly useful and gave up on it after the hackathon. Still, it was a cool project.
[1] http://www.seas.upenn.edu/~harmony/
[2] http://www.cis.upenn.edu/~bcpierce/papers/lenses-etapsslides...
[3] http://www.cis.upenn.edu/~bcpierce/papers/harmful-mfps.pdf
I don't think anything happened to it since the hackathon. Judging by own experience with hackathons, I wouldn't expect too much in the way of code quality. (Reading some of my old hackathon code still makes me shudder :)).
using (var file = File.Open("foo.txt"))
{
...
}(with-open-file (output "foo.txt" :direction :output :if-exists :supersede) (print-foo output))
But Common Lisp is Lisp.
If you want to abstract the pattern out even further, then all you are doing is running a function within a certain context and then getting everything back to normal. Using under in J, scoping it out with ruby, or using with-open in Lisp are all examples of the pattern, just different ways of thinking about it.
twixt (expression1, expression2)
statement1
If expression1 is true, then statement1 will be executed followed by expression2 in that order. The twixt statement guarantees that expression2 is always executed if expression1 is true, similarly to how "finally" works in java.Am I missing something here? How is that different from, say:
if (expression1) {
statement1
expression2
}
?More interestingly, Nickle has support for continuations, so if statement1 generates a continuation and makes a non-local exit, then expression2 is evaluated before that exit, and expression1 is evaluated before the continuation is resumed.
In other words, statement1 is always bracketed by expression1/expression2, even in the presence of non-local control flow.
For (stupid) example:
def reverse(x) as inversible with(reverse): #special case - reverse is itself inverse function
x = x.reversed() #I'm too lazy to code this by hand
def lastFive(x) as pure: #let's say language checks if pure function only uses pure and inversable functions
return x[:5] under reverse
Here lastFive is pure function even thought reverse is destructive.This assumes everybody sticks to one definition of reversing something, in this case functions f and g are inverse of each other, when after invoking f(x), doing only pure or reversable things to x, and invoking g(x), x is unchanged.
And I don't know if this will be useful for anything - the only point seems to be avoiding making copies and still making pure functions. But resulting code, while semanticaly pure, is not threadsafe. So I don't know if it's worth anything.
For instance, when we have x+y=z and know only x and z, we need to reverse the equation to have y=z-x. The system was built on nodes which would propagate change (a-la events).
IMO, python's with statement with __enter__ and __exit__ looks mostly like this.
Make the headline informative instead, if you have great content people will read and share it anyway.
Better version of this headline:
XXXX: A programming idiom that helps you do YYYY
CL and Clojure could easily support a generic with macro requiring that there be an open and close method for the resource in question.
Typically this idiom is the function call itself. The act of sipping coffee is the point of the function, and picking up the cup and putting the cup back down are the whole point of the function call.
I was never convinced this was a great idiom. BETA didn't become very popular, in any event.
http://docs.racket-lang.org/reference/createclass.html?q=inn...)
During my dark past as a VB programmer (early-mid 90's) I even indented the code for pairs like this.
http://www.jsoftware.com/help/dictionary/d202n.htm
Obverse is defined in a table and some special cases, and there's a built in "this is the obverse of that" instruction.
You could easily tie square/sort together as a pair in Python and it wouldn't be significantly different.
Under(square, sum, mylist) or whatever.
File.open(name, mode) receives a block, executes it, and then closes the file.
A programming language can't figure out what the inverse of open() is without someone somewhere telling it to close(). The point of the idiom is to have a library figure that out so that users don't have to. Therefore, Ruby supports it fully (there where API developers are sane, that is).
Case by case, the block scoping idiom is a good way to handle it.