📜 ⬆️ ⬇️

Software idiom you've never heard of

Here are some sequences of events:

Take the rake out of the shed, scrape the leaves in the yard, then put the rake back to the shed.

Fly to Seattle, see the sights, then fly home.
')
Insert the key in the door, open it, then pull the key out of the door.

Turn on the phone screen, see the time, then turn it off.

See the pattern? You do something, then do something else, and then cancel the first action. Or, more precisely, the last step is the reverse of the first. If you know about this template, you will see it everywhere. Take a mug, sip coffee, put a mug. The same thing is everywhere in the code.

Open the file, read the contents, close the file.

Allocate a block of memory, use it for something, free up memory.

Load the contents of the memory cell in the register, change it, send back to memory.

Although it is easy to explain and give examples, it is not easy to put into practice. We need an operation that looks like idiom (Function1, Function2) so that we can write the above example “open file ...” like idiom (Open, Read) . The difficulty is that there must be some programmatic way to determine that the inverse element for “opening” is “closing”. Are there any programming languages ​​in which inversion exists for functions?

Surprisingly, there is: j . And this idiom that I'm talking about is built in as a function of J, which is called under . That is, in Russian, and not in the laconic syntax J, the example with the opening of the file would have sounded like “read under open”.

One of the unobvious applications of under in J is the calculation of the modulus of the vector. Here is a simple algorithm: square each member, put them together, and then extract the square root of the result. Hmm ... the third step is the reverse for the first. Addition under the square. Or, in real J code:

mag =: +/&.:*: 

+/ - this is an addition. The sequence &, periods and colons means the function under , and *: is squaring.

In some other programming languages ​​there are peculiar analogs of the function under . For example, in Ruby you can open a file with an indication of the necessary action on this file, and then it will close itself at the end of the specified action.

 File.open('file.txt', 'w') {|file| #   «file.txt»   («w» — write) file.puts 'Wrote some text.' } 

Source: https://habr.com/ru/post/135739/


All Articles