maXbox Starter 31 Closures Tutorial
-
Upload
max-kleiner -
Category
Documents
-
view
226 -
download
0
Transcript of maXbox Starter 31 Closures Tutorial
-
8/11/2019 maXbox Starter 31 Closures Tutorial
1/13
maXbox Starter 31
Start with Closures
1.1 A Function Block in a Box
Today we step through a topic of closures.
One of the questions that comes up when learning closures is how theycan be useful when they're no less verbose as traditional methods ofcallbacks, IoC and delegation. The answer is that closures or methods
don't have to be so verbose they are reusable. !hat are closures"
They are a block of code plus the bindings to the environment they
came from #$agusa Idiom % function ob&ect.
(irst we will start with an anonymous method"
procedure
begin
writeln('Anonymous method has executed');
end
This isn't very different from a normal procedure. )ou'll notice that theprocedure has no name. )ou'll also notice the missing semicolon after thefinal end like others in ma*bo+ #whitespacing.!ithout a name, we have to call them by a reference. aybe you know aprocedure type as long ago used in many languages before ob&ectoriented coding was up"
Type
TMath_Func = PROCEDURE(varx: single);
-uch a procedure type can be called or passed by reference.
-
8/11/2019 maXbox Starter 31 Closures Tutorial
2/13
-
8/11/2019 maXbox Starter 31 Closures Tutorial
3/13
That reference can be a variable to which the method is assigned.
var
fct$x:TMath_Func;
var
myAnonymousMethod: Troc;
Only procedures that are not contained in other procedures can be
assigned as the values of procedure variables. -tandard procedurescannot be assigned as values of procedure variables.
4ow we step from anonymous methods and p/types to a closure.
)ou remember the definition"
A block of code plus the bindings to the environment they came from.
This is the formal thing that sets closures apart from function pointers,procedure types and similar techniques.
0s more 6things6 on planet 7arth are converted to the inventory set ofdigitally connected Internet devices, the roles and responsibilities of webdevelopers and technology managers will need to evolve with closures.
5ope you did already work with the -tarter 8 till 9:"
http://sourceforge.net/apps/mediawiki/maxbox/
!e start a closure with simplification, the image below is my sight of a
closure" the cards are functions with red variables of game state which areenclosed by a black bo+ and can be called by ref name behind.
-implification" )our classes are small and your methods too you;ve said
everything and you;ve removed the last piece of unnecessary code.
1.1.1 et the Closure Code
Closures are reusable blocks of code that capture the environment andcan be passed around as method arguments for immediate or deferrede+ecution.
3
http://sourceforge.net/apps/mediawiki/maxbox/http://sourceforge.net/apps/mediawiki/maxbox/ -
8/11/2019 maXbox Starter 31 Closures Tutorial
4/13
The term closure is very often treated as a synonym for the term anony/mous methods. Though closures are specific to anonymous methods, theyare not the same concept. !hy2
The scopeis missing as I want to show you now.
)ou see that our p/type has a parameter + through which I pass thecurrent base value to the const with e+ponent
-
8/11/2019 maXbox Starter 31 Closures Tutorial
5/13
The function that's returned is called a closure.
!hen a function is written enclosed in another function, it has full accessto local variables from the enclosing function this feature is also calledle+ical scoping.
Closures create another scope which includes any symbols used by theanonymous method but which are not declared inside the method itself,
like the above parameter n. This scopeis then bound to the anonymousmethod and follows it everywhere it goes.
The image below declares this conte+t with arguments which a caller canfollow in another conte+t.
-o now you're wondering why I &ust spent this time e+plaining closureswhen it works &ust like a nested method anyway and you don't have totake any steps to make it work. !ithout closures you can think of"
A In C or ascal you think as a function pointer or procedure type
A In 1ava as an anonymous inner class
A In Belphi or C you would consider a delegate.
The reason is because a closure is not really a direct access to the symbolsin the outer scope #its sort of compiler magic D see appendi+ so you needthe old basics on the other hand a closure is more fle+ible and reusablethan all the others.
If you have ever written a function that returned another function, you
probably may have used the closure concept even without knowing aboutthem.
!e should keep 9 things in mind"
"
-
8/11/2019 maXbox Starter 31 Closures Tutorial
6/13
8. The ability to bind to local variables is part of that, but I think the bigreason is that the notation to use them is simple and clear.
E. 1ava's anonymous inner classes can access locals / but only if theyare declared final.
9. !ith closures we can avoid"
=ad 4aming #no naming convention
Buplicated Code #side effects
Fong ethods #to much code and temporary (ields #confusion
Fong arameter Fist #Ob&ect is missing
Bata Classes #no methods
A Farge Class and Class with too many delegating methods
A Coupled classes
!ithout closures, you would use more upper variables using parametersand you would repeat yourself because you cant pass your function toanother function like the following counter e+. stresses"
functionnew,ounter ()
local i:=*
return function() 55anonymous function
i:=i 6!
return i
end
end
c!:=new,ounter()
%rint(c!()) 551!
%rint(c!()) 551#
)ou can pass the counter function to print as many times you like and thescope as the local var goes with the result of the call1, otherwise it wouldbe initialise by : over and over again@
1#ote that this means that result cannot li$e onl% in C&'S()*S
+
-
8/11/2019 maXbox Starter 31 Closures Tutorial
7/13
-imply put, a closure is a function plus all it needs to access its upvaluescorrectly #local vars in most of the time. If we call new,ounteragain, itwill create a new local variable i, so we will get a new closure, acting overthat new variable #and you avoid globals too@"
c# =new,ounter()
%rint(c#()) 551!
%rint(c!()) 551$
%rint(c#()) 551#
!hy is that so interesting and important2 =ecause functions are in a
closure sense first/class values with memory of scope.
1.1.2 Some ,ractise
0s you already know the tool is split up into the toolbar across the top, theeditor or code part in the centre and the output window at the bottom.Change that in the menu %view at our own style.
In ma*bo+ you will not call closures only callbacks%p/types in a script,so the part above is also an introduction to other languages but closuresare in the pipe of m*
-
8/11/2019 maXbox Starter 31 Closures Tutorial
8/13
o some lengthy %rocess to show hourglass cursor
finally
9creen+,ursor:= 8ld,ursor;
end;
end;
-o, this kind of boilerplate construct calls for an anonymous method orcallback method"
typeTroc =procedure;
procedurere%eatroc;
var i:integer;
begin
fori:=!to
-
8/11/2019 maXbox Starter 31 Closures Tutorial
9/13
0 closure is created containing the message parameter, fn# is e+ecutedquite some time after the call to AlertThis?aterhas returned, yet fn#still has access to the original content of message@
!: he (0 of the Closure pp
": browser set of a closure
The increase in importance of web services, however, has made it possibleto use dynamic languages #where types are not strictly enforced atcompile time for large scale development. Fanguages such as ython,$uby and 5 support closures.
-cheme was the first language to introduce closures, allowing full
le+ical scoping, simplifying many types of programming style.
1.1.3 Closure 'bects
Close to the end of the last part some knowledge about ob&ect functions.Closure ob&ects can be divided into three basic types, which reflect how aclosure was initiated and what a local ob&ect is referenced to.
-
8/11/2019 maXbox Starter 31 Closures Tutorial
10/13
These 9 are
A !hen a function is written enclosed in another function, it has fullaccess to local variables from the enclosing function thisfeature is called le+ical scoping.
A 7valuating a closure e+pression produces a closure ob&ect as areference.
A The closure ob&ect can later be invoked, which results in e+ecutionof the body, yielding the value of the e+pression #if one waspresent to the invoker.
Therefore the inner function can access variables in the calling function,
i.e. its closure.
The compiler has to make decisions about where the data comes from andwhat it can do with that data. -ometimes it will determine that a closure is
not possible and will give you simply an error.
+: the 4'X5 rduino and the (0 is #' a closure 678
19
-
8/11/2019 maXbox Starter 31 Closures Tutorial
11/13
1.2 Conclusion
Closures improve automation and integration of new methods, bettertestability, efficiency and readability #simplification and above all reuse.
5ow many times have you written a piece of code and thought ?Iwish I could reuse this block of codeK2
5ow many times have you re/factored e+isting code to removeredundancies2
5ow many times have you written the same block of code more thanonce before realising that an abstraction e+ists2
Code that support closures allows functions with very little synta+ and lessredundancy. !hile this might not seem an important point, I believe it'scrucial / it's the key to make it natural to use them frequently. Fook at Fispor or $uby and you'll see closures all over the place.
eedback ;
max;kleiner.com
&iterature:
eb of hings:
http://www.softwareschule.ch/download/Closures?@urich2912?2.pdf
http://www.softwareschule.ch/download/closures?report.pdf
http://www.shutupandship.com/2912/91/p%thon7closures7explained.html
http://gafter.blogspot.com/299-/91/definition7ofclosures.html
http://www.softwareschule.ch/download/rduino?C?291!?+?basta?box.pdf
http://www.softwareschule.ch/maxbox.htm
A Bichael 4olin5 Closure: he Definiti$e uideE5 'F)eill% Bedia6 uflage: 1 G29. 'ktober 29198.
http://sourceforge.net/proects/maxbox
http://sourceforge.net/apps/mediawiki/maxbox/
http://sourceforge.net/proects/delphiwebstart
11
mailto:[email protected]://www.softwareschule.ch/download/Closures_zurich2012_2.pdfhttp://www.softwareschule.ch/download/closures_report.pdfhttp://www.shutupandship.com/2012/01/python-closures-explained.htmlhttp://gafter.blogspot.com/2007/01/definition-ofclosures.htmlhttp://www.softwareschule.ch/maxbox.htmhttp://sourceforge.net/projects/maxboxhttp://sourceforge.net/apps/mediawiki/maxbox/http://sourceforge.net/projects/delphiwebstartmailto:[email protected]://www.softwareschule.ch/download/Closures_zurich2012_2.pdfhttp://www.softwareschule.ch/download/closures_report.pdfhttp://www.shutupandship.com/2012/01/python-closures-explained.htmlhttp://gafter.blogspot.com/2007/01/definition-ofclosures.htmlhttp://www.softwareschule.ch/maxbox.htmhttp://sourceforge.net/projects/maxboxhttp://sourceforge.net/apps/mediawiki/maxbox/http://sourceforge.net/projects/delphiwebstart -
8/11/2019 maXbox Starter 31 Closures Tutorial
12/13
-
8/11/2019 maXbox Starter 31 Closures Tutorial
13/13
111delgenerate_%ower_func
111raised_to_&(#)
!4
:H%h%I H%h%I # define a function within a function and return it to thecallin scope - # a inner function can access ariables in a callin
function, its closure
deftimes(n):
def_f(x):
returnx0n
return_f
t$=times($)
printt$#printt$(C)# "
H%h%I
eretheinnerfunction_f()istheloc7ofcodeoftheclosure"similartothela!bdacodeinthefirstexam%le+
erean emedded microcontroller system seems li7e a closure as afunctional %rogramming with loc7s of code:
RTClock: Arduino by Silvia Rothen
http://www.ecotronics.ch/ecotron/arduinocheatsheet.htm
13
http://www.ecotronics.ch/ecotron/arduinocheatsheet.htmhttp://www.ecotronics.ch/ecotron/arduinocheatsheet.htm