{"id":611,"date":"2013-01-24T11:00:13","date_gmt":"2013-01-24T16:00:13","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=611"},"modified":"2013-01-24T10:41:55","modified_gmt":"2013-01-24T15:41:55","slug":"introduction-to-functional-programming-with-anonymous-functions-part-2","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2013\/01\/24\/introduction-to-functional-programming-with-anonymous-functions-part-2\/","title":{"rendered":"Introduction to Functional Programming with Anonymous Functions, Part 2"},"content":{"rendered":"<!DOCTYPE html\r\n  PUBLIC \"-\/\/W3C\/\/DTD HTML 4.01 Transitional\/\/EN\">\r\n<style type=\"text\/css\">\r\n\r\nh1 { font-size:18pt; }\r\nh2.titlebg { font-size:13pt; }\r\nh3 { color:#4A4F55; padding:0px; margin:5px 0px 5px; font-family:Arial, Helvetica, sans-serif; font-size:11pt; font-weight:bold; line-height:140%; border-bottom:1px solid #d6d4d4; display:block; }\r\nh4 { color:#4A4F55; padding:0px; margin:0px 0px 5px; font-family:Arial, Helvetica, sans-serif; font-size:10pt; font-weight:bold; line-height:140%; border-bottom:1px solid #d6d4d4; display:block; }\r\n   \r\np { padding:0px; margin:0px 0px 20px; }\r\nimg { padding:0px; margin:0px 0px 20px; border:none; }\r\np img, pre img, tt img, li img { margin-bottom:0px; } \r\n\r\nul { padding:0px; margin:0px 0px 20px 23px; list-style:square; }\r\nul li { padding:0px; margin:0px 0px 7px 0px; background:none; }\r\nul li ul { padding:5px 0px 0px; margin:0px 0px 7px 23px; }\r\nul li ol li { list-style:decimal; }\r\nol { padding:0px; margin:0px 0px 20px 0px; list-style:decimal; }\r\nol li { padding:0px; margin:0px 0px 7px 23px; list-style-type:decimal; }\r\nol li ol { padding:5px 0px 0px; margin:0px 0px 7px 0px; }\r\nol li ol li { list-style-type:lower-alpha; }\r\nol li ul { padding-top:7px; }\r\nol li ul li { list-style:square; }\r\n\r\npre, tt, code { font-size:12px; }\r\npre { margin:0px 0px 20px; }\r\npre.error { color:red; }\r\npre.codeinput { padding:10px; border:1px solid #d3d3d3; background:#f7f7f7; }\r\npre.codeoutput { padding:10px 11px; margin:0px 0px 20px; color:#4c4c4c; }\r\n\r\n@media print { pre.codeinput, pre.codeoutput { word-wrap:break-word; width:100%; } }\r\n\r\nspan.keyword { color:#0000FF }\r\nspan.comment { color:#228B22 }\r\nspan.string { color:#A020F0 }\r\nspan.untermstring { color:#B20000 }\r\nspan.syscmd { color:#B28C00 }\r\n\r\n.footer { width:auto; padding:10px 0px; margin:25px 0px 0px; border-top:1px dotted #878787; font-size:0.8em; line-height:140%; font-style:italic; color:#878787; text-align:left; float:none; }\r\n.footer p { margin:0px; }\r\n\r\n  <\/style><div class=\"content\"><!--introduction--><p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/225094\">Tucker McClure<\/a> is an Application Engineer with The MathWorks. He spends his time helping our customers accelerate their work with the right tools and problem-solving techniques. Today, he'll be discussing how \"functional programming\" can help create brief and powerful MATLAB code.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#1768cbcf-cd3a-4edf-a484-4b2c26f6fa39\">Recap<\/a><\/li><li><a href=\"#b0cc1edc-05b5-4668-a8ea-3752f7f74804\">Anonymous Function Recursion<\/a><\/li><li><a href=\"#db344cb8-ae1b-4b25-8071-af3883a49003\">Helpers<\/a><\/li><li><a href=\"#eadbce51-e1cc-46e9-80ea-58f1108621fc\">Executing Multiple Statements<\/a><\/li><li><a href=\"#08367508-8f1c-490e-83ed-ab6204d28e95\">To Be Continued<\/a><\/li><\/ul><\/div><h4>Recap<a name=\"1768cbcf-cd3a-4edf-a484-4b2c26f6fa39\"><\/a><\/h4><p>For Part 1, click <a href=\"https:\/\/blogs.mathworks.com\/loren\/2013\/01\/10\/introduction-to-functional-prog\">here<\/a>.<\/p><p>Last time, we said that functional programming was marked by storing functions as variables (function handles) and working with functions that act on other functions. We put these ideas together to implement our own version of a <tt>map<\/tt> function for handling multiple inputs and outputs from multiple functions simultaneously, and we created <tt>iif<\/tt>, an \"inline if\", to allow the use of conditional statements inside of anonymous functions. So how might we work with recursive functions -- functions of themselves? We'll see how a functional programming style allows us to implement recursive functionality inside anonymous functions, and this will pave the way for the final part, in which we'll implement loops, without ever using <tt>for<\/tt> or <tt>while<\/tt> (which we can't use in anonymous functions).<\/p><p>Before we get started, let's implement <tt>iif<\/tt> again; we're going to need it frequently.<\/p><pre class=\"codeinput\">iif = @(varargin) varargin{2*find([varargin{1:2:end}], 1, <span class=\"string\">'first'<\/span>)}();\r\n<\/pre><h4>Anonymous Function Recursion<a name=\"b0cc1edc-05b5-4668-a8ea-3752f7f74804\"><\/a><\/h4><p>Recall that a recursive function is a function that calls itself. It therefore needs some way to refer to itself. When we write an anonymous function, it isn't \"named\" (hence, \"anonymous\"), so it can't call itself by name. How can we get around this?<\/p><p>Let's start with a Fibonacci sequence example. Recall that the nth number of the Fibonacci sequence is the sum of the previous two numbers, starting with 1 and 1, yielding 1, 1, 2, 3, 5, 8, 13, 21, etc. This is easy to implement recursively.<\/p><pre>   fib = @(n) iif(n &lt;= 2, 1, ...                    % First two numbers\r\n                  true,   @() fib(n-1) + fib(n-2)); % All later numbers<\/pre><p>But hey, that can't work! We haven't defined <tt>fib<\/tt> yet, so how could this anonymous function call it? In fact, the anonymous function will never \"know\" we're referring to it as <tt>fib<\/tt>, so this won't work at all. Therefore, instead of trying to call <tt>fib<\/tt> directly, let's provide another input: the handle of a function to call, <tt>f<\/tt>.<\/p><pre class=\"codeinput\">fib = @(f, n) iif(n &lt;= 2, 1, <span class=\"keyword\">...<\/span><span class=\"comment\">                      % First two numbers<\/span>\r\n                  true,   @() f(f, n-1) + f(f, n-2)); <span class=\"comment\">% All later numbers<\/span>\r\n<\/pre><p>Getting closer. Now, if we pass <tt>fib<\/tt> <i>to<\/i> <tt>fib<\/tt> along with the number we want, it will call <tt>fib<\/tt>, passing in <tt>fib<\/tt> as the first argument, recursively until we get our answer.<\/p><pre class=\"codeinput\">fib(fib, 6)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     8\r\n<\/pre><p>Ok, that's right. The sixth number of the sequence is 8. On the other hand, the syntax we've created is terrible. We have to provide the function to itself? I'd rather not. Instead, let's just write a new function that hands <tt>fib<\/tt> to <tt>fib<\/tt> along with the input <tt>n<\/tt>.<\/p><pre class=\"codeinput\">fib2 = @(n) fib(fib, n);\r\n\r\nfib2(4)\r\nfib2(5)\r\nfib2(6)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     3\r\nans =\r\n     5\r\nans =\r\n     8\r\n<\/pre><p>That's a lot closer to what we want, but there's one more step. Let's write a function called <tt>recur<\/tt> to hand a function handle to itself, along with any other arguments. This makes recursion less cumbersome.<\/p><pre class=\"codeinput\">recur = @(f, varargin) f(f, varargin{:});\r\n<\/pre><p>That was simple, so now let's re-write <tt>fib<\/tt>. The first argument to <tt>recur<\/tt> is the function, which we'll define inline. The second is <tt>n<\/tt>. That's all there is to it. It now reads as \"Recursively call a function that, if <tt>k &lt;= 2<\/tt>, returns one, and otherwise returns the recursive function of <tt>k-1<\/tt> plus that of <tt>k-2<\/tt>, starting with the user's input <tt>n<\/tt>.\" (If it doesn't read quite this clearly at first, that's ok. It takes some getting used to. Comment liberally if necessary!)<\/p><pre class=\"codeinput\">fib = @(n) recur(@(f, k) iif(k &lt;= 2, 1, <span class=\"keyword\">...<\/span>\r\n                             true,   @() f(f, k-1) + f(f, k-2)), <span class=\"keyword\">...<\/span>\r\n                 n);\r\n<\/pre><p>And we can find the first ten numbers of the sequence via <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/arrayfun.html\">arrayfun<\/a>.<\/p><pre class=\"codeinput\">arrayfun(fib, 1:10)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     1     1     2     3     5     8    13    21    34    55\r\n<\/pre><p>Factorial (f(n) = 1 * 2 * 3 * ... n) is another easy operation to represent recursively.<\/p><pre class=\"codeinput\">factorial = @(n) recur(@(f, k) iif(k == 0, 1, <span class=\"keyword\">...<\/span>\r\n                                   true,   @() k * f(f, k-1)), n);\r\narrayfun(factorial, 1:7)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n  Columns 1 through 6\r\n           1           2           6          24         120         720\r\n  Column 7\r\n        5040\r\n<\/pre><p>A number to an integer power has a nearly identical form. Here's <tt>4.^(0:5)<\/tt>.<\/p><pre class=\"codeinput\">pow = @(x, n) recur(@(f, k) iif(k == 0, 1, <span class=\"keyword\">...<\/span>\r\n                                true,   @() x * f(f, k-1)), n);\r\narrayfun(@(n) pow(4, n), 0:5)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n           1           4          16          64         256        1024\r\n<\/pre><p>That was a big step for anonymous functions, using both recursion and an inline conditional together with ease. Like <tt>map<\/tt> and <tt>iif<\/tt>, <tt>recur<\/tt>, looks strange at first, but once it's been seen, it's hard to forget how it works (just make one of the inputs a function handle and pass it to itself). And recursion doesn't have to stop at interesting mathematical sequences of numbers. For instance, in the next part, we'll use this to implement loops in, but first, we'll need a some helper functions and a good way to execute multiple statements in an anonymous function.<\/p><h4>Helpers<a name=\"db344cb8-ae1b-4b25-8071-af3883a49003\"><\/a><\/h4><p>These little functions are useful in many circumstances, and we're going to need <tt>curly<\/tt> frequently.<\/p><pre class=\"codeinput\">paren = @(x, varargin) x(varargin{:});\r\ncurly = @(x, varargin) x{varargin{:}};\r\n<\/pre><p>They allow us to write <tt>x(3, 4)<\/tt> as <tt>paren(x, 3, 4)<\/tt> and similarly for curly braces. That is, now we can think of parentheses and curly braces as functions! At first this might not seem useful. However, imagine writing a function to return the width and height of the screen. The data we need is available from this call:<\/p><pre class=\"codeinput\">get(0, <span class=\"string\">'ScreenSize'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n           1           1        1920        1200\r\n<\/pre><p>However, we don't need those preceeding ones. We could save the output to a variable, say <tt>x<\/tt>, and then access x(3:4), but if we need this in an anonymous function, we can't save to a variable. How do we access just elements 3 and 4? There are numerous ways, but <tt>paren<\/tt> and <tt>curly<\/tt> are similar to constructs found in other languages and are easy to use, so we'll use those here.<\/p><p>Now we can write our <tt>screen_size<\/tt> function to return just the data we want.<\/p><pre class=\"codeinput\">screen_size = @() paren(get(0, <span class=\"string\">'ScreenSize'<\/span>), 3:4);\r\n\r\nscreen_size()\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n        1920        1200\r\n<\/pre><p>While on the subject, note that we can actually use any number of indices or even ':'.<\/p><pre class=\"codeinput\">magic(3)\r\nparen(magic(3), 1:2, 2:3)\r\nparen(magic(3), 1:2, :)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     8     1     6\r\n     3     5     7\r\n     4     9     2\r\nans =\r\n     1     6\r\n     5     7\r\nans =\r\n     8     1     6\r\n     3     5     7\r\n<\/pre><p>We do the same with the curly braces. Here, the regular expression pattern will match both 'rain' and 'Spain', but we'll only select the second match.<\/p><pre class=\"codeinput\">spain = curly(regexp(<span class=\"string\">'The rain in Spain....'<\/span>, <span class=\"string\">'\\s(\\S+ain)'<\/span>, <span class=\"string\">'tokens'<\/span>), 2)\r\n<\/pre><pre class=\"codeoutput\">spain = \r\n    'Spain'\r\n<\/pre><p>(Click for <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/regexp.html\">Regexp help<\/a>.)<\/p><p>It also works with ':' (note that the single quotes are required).<\/p><pre class=\"codeinput\">[a, b] = curly({<span class=\"string\">'the_letter_a'<\/span>, <span class=\"string\">'the_letter_b'<\/span>}, <span class=\"string\">':'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">a =\r\nthe_letter_a\r\nb =\r\nthe_letter_b\r\n<\/pre><h4>Executing Multiple Statements<a name=\"eadbce51-e1cc-46e9-80ea-58f1108621fc\"><\/a><\/h4><p>With <tt>curly<\/tt> in place, let's examine something a little different. Consider the following:<\/p><pre class=\"codeinput\">do_three_things = @() {fprintf(<span class=\"string\">'This is the first thing.\\n'<\/span>), <span class=\"keyword\">...<\/span>\r\n                       fprintf(<span class=\"string\">'This is the second thing.\\n'<\/span>), <span class=\"keyword\">...<\/span>\r\n                       max(eig(magic(3)))};\r\n\r\ndo_three_things()\r\n<\/pre><pre class=\"codeoutput\">This is the first thing.\r\nThis is the second thing.\r\nans = \r\n    [25]    [26]    [15]\r\n<\/pre><p>We've executed three statements on a single line. All of the outputs are stored in the cell array, so we have three elements in the cell array. The first two outputs are actually garbage as far as we're concerned (they're just the outputs from <tt>fprintf<\/tt>, which is the number of bytes written, which we don't care about at all). The last output is from <tt>max(eig(magic(3)))<\/tt>; That is, the biggest eigenvalue of <tt>magic(3)<\/tt> is exactly 15. Let's say we just wanted that final value, the eigenvalue. It's the third element of the cell array, so we can grab it with <tt>curly<\/tt>.<\/p><pre class=\"codeinput\">do_three_things = @() curly({fprintf(<span class=\"string\">'This is the first thing.\\n'<\/span>), <span class=\"keyword\">...<\/span>\r\n                             fprintf(<span class=\"string\">'This is the second thing.\\n'<\/span>), <span class=\"keyword\">...<\/span>\r\n                             max(eig(magic(3)))}, 3);\r\n\r\ndo_three_things()\r\n<\/pre><pre class=\"codeoutput\">This is the first thing.\r\nThis is the second thing.\r\nans =\r\n           15\r\n<\/pre><p>For a more complex example, let's say we want to write a function to:<\/p><div><ol><li>Create a small figure in the middle of the screen<\/li><li>Plot some random points<\/li><li>Return the handles of the figure and the plot<\/li><\/ol><\/div><p>Then by storing all of the outputs in a cell array and using <tt>curly<\/tt> to access the outputs we care about, we can make a multi-line function with multiple outputs, all in a simple anonymous function.<\/p><pre class=\"codeinput\">dots = @() curly({<span class=\"keyword\">...<\/span>\r\n    figure(<span class=\"string\">'Position'<\/span>, [0.5*screen_size() - [100 50], 200, 100], <span class=\"keyword\">...<\/span>\r\n           <span class=\"string\">'MenuBar'<\/span>,  <span class=\"string\">'none'<\/span>), <span class=\"keyword\">...<\/span><span class=\"comment\">                % Position the figure<\/span>\r\n    plot(randn(1, 100), randn(1, 100), <span class=\"string\">'.'<\/span>)}, <span class=\"keyword\">...<\/span><span class=\"comment\">  % Plot random points<\/span>\r\n    <span class=\"string\">':'<\/span>);                                          <span class=\"comment\">% Return everything<\/span>\r\n\r\n[h_figure, h_dots] = dots()\r\n<\/pre><pre class=\"codeoutput\">h_figure =\r\n     3\r\nh_dots =\r\n          187\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2013\/functional_programming_techniques_2_01.png\" alt=\"\"> <p>(As a quick aside, note that if a statement doesn't return anything, we can't put it in a cell array, and so we can't use it this way. There are ways around this, discussed <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/39735-functional-programming-constructs\">here<\/a>.)<\/p><h4>To Be Continued<a name=\"08367508-8f1c-490e-83ed-ab6204d28e95\"><\/a><\/h4><p>Today, we've come a long way, from a simple condition through recursion and executing multiple statements. Here's a roundup of the functions so far.<\/p><pre class=\"codeinput\">map     = @(val, fcns) cellfun(@(f) f(val{:}), fcns);\r\nmapc    = @(val, fcns) cellfun(@(f) f(val{:}), fcns, <span class=\"string\">'UniformOutput'<\/span>, 0);\r\niif     = @(varargin) varargin{2*find([varargin{1:2:end}], 1, <span class=\"string\">'first'<\/span>)}();\r\nrecur   = @(f, varargin) f(f, varargin{:});\r\nparen   = @(x, varargin) x(varargin{:});\r\ncurly   = @(x, varargin) x{varargin{:}};\r\n<\/pre><p>These can also be found <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/39735-functional-programming-constructs\">here<\/a>, implemented as regular MATLAB functions that can be kept on the path.<\/p><p>Next time, we'll look at loops. Until then, have you worked with functions such as <tt>paren<\/tt> or <tt>curly<\/tt>? How else are people implementing these or similar operations? Let us know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=611#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_785282659a42421c916b8b165e146cdb() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='785282659a42421c916b8b165e146cdb ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 785282659a42421c916b8b165e146cdb';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        copyright = 'Copyright 2013 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n\r\n        d.title = title + ' (MATLAB code)';\r\n        d.close();\r\n    }   \r\n     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_785282659a42421c916b8b165e146cdb()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2012b<br><\/p><p class=\"footer\"><br>\r\n      Published with MATLAB&reg; R2012b<br><\/p><\/div><!--\r\n785282659a42421c916b8b165e146cdb ##### SOURCE BEGIN #####\r\n%% Introduction to Functional Programming with Anonymous Functions, Part 2\r\n%\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/225094 \r\n% Tucker McClure> is an Application Engineer with The MathWorks. He spends\r\n% his time helping our customers accelerate their work with the right tools\r\n% and problem-solving techniques. Today, he'll be discussing how\r\n% \"functional programming\" can help create brief and powerful MATLAB code.\r\n\r\n%% Recap\r\n% For Part 1, click\r\n% <https:\/\/blogs.mathworks.com\/loren\/2013\/01\/10\/introduction-to-functional-prog\r\n% here>.\r\n%\r\n% Last time, we said that functional programming was marked by storing\r\n% functions as variables (function handles) and working with functions that\r\n% act on other functions. We put these ideas together to implement our own\r\n% version of a |map| function for handling multiple inputs and outputs from\r\n% multiple functions simultaneously, and we created |iif|, an \"inline if\",\r\n% to allow the use of conditional statements inside of anonymous functions.\r\n% So how might we work with recursive functions REPLACE_WITH_DASH_DASH functions of themselves?\r\n% We'll see how a functional programming style allows us to implement\r\n% recursive functionality inside anonymous functions, and this will pave\r\n% the way for the final part, in which we'll implement loops, without ever \r\n% using |for| or |while| (which we can't use in anonymous functions).\r\n% \r\n% Before we get started, let's implement |iif| again; we're going to need \r\n% it frequently.\r\n\r\niif = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();\r\n\r\n%% Anonymous Function Recursion\r\n% Recall that a recursive function is a function that calls itself. It \r\n% therefore needs some way to refer to itself. When we write an anonymous \r\n% function, it isn't \"named\" (hence, \"anonymous\"), so it can't call itself\r\n% by name. How can we get around this?\r\n%\r\n% Let's start with a Fibonacci sequence example. Recall that the nth number\r\n% of the Fibonacci sequence is the sum of the previous two numbers, \r\n% starting with 1 and 1, yielding 1, 1, 2, 3, 5, 8, 13, 21, etc. This is \r\n% easy to implement recursively.\r\n%\r\n%     fib = @(n) iif(n <= 2, 1, ...                    % First two numbers\r\n%                    true,   @() fib(n-1) + fib(n-2)); % All later numbers\r\n%\r\n% But hey, that can't work! We haven't defined |fib| yet, so how could\r\n% this anonymous function call it? In fact, the anonymous function will\r\n% never \"know\" we're referring to it as |fib|, so this won't work at all. \r\n% Therefore, instead of trying to call |fib| directly, let's provide\r\n% another input: the handle of a function to call, |f|.\r\n\r\nfib = @(f, n) iif(n <= 2, 1, ...                      % First two numbers            \r\n                  true,   @() f(f, n-1) + f(f, n-2)); % All later numbers\r\n\r\n%%\r\n% Getting closer. Now, if we pass |fib| _to_ |fib| along with the number we\r\n% want, it will call |fib|, passing in |fib| as the first argument, \r\n% recursively until we get our answer.\r\n\r\nfib(fib, 6)\r\n\r\n%%\r\n% Ok, that's right. The sixth number of the sequence is 8. On the other \r\n% hand, the syntax we've created is terrible. We have to provide the\r\n% function to itself? I'd rather not. Instead, let's just write a new\r\n% function that hands |fib| to |fib| along with the input |n|.\r\n\r\nfib2 = @(n) fib(fib, n);\r\n\r\nfib2(4)\r\nfib2(5)\r\nfib2(6)\r\n\r\n%%\r\n% That's a lot closer to what we want, but there's one more step. Let's\r\n% write a function called |recur| to hand a function handle to itself, \r\n% along with any other arguments. This makes recursion less cumbersome.\r\n\r\nrecur = @(f, varargin) f(f, varargin{:});\r\n\r\n%%\r\n% That was simple, so now let's re-write |fib|. The first argument to\r\n% |recur| is the function, which we'll define inline. The second is |n|.\r\n% That's all there is to it. It now reads as \"Recursively call a function\r\n% that, if |k <= 2|, returns one, and otherwise returns the recursive\r\n% function of |k-1| plus that of |k-2|, starting with the user's input\r\n% |n|.\" (If it doesn't read quite this clearly at first, that's ok. It\r\n% takes some getting used to. Comment liberally if necessary!)\r\n\r\nfib = @(n) recur(@(f, k) iif(k <= 2, 1, ...\r\n                             true,   @() f(f, k-1) + f(f, k-2)), ...\r\n                 n);\r\n\r\n%%\r\n% And we can find the first ten numbers of the sequence via \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/arrayfun.html arrayfun>.\r\n\r\narrayfun(fib, 1:10)\r\n\r\n%%\r\n% Factorial (f(n) = 1 * 2 * 3 * ... n) is another easy operation to \r\n% represent recursively.\r\n\r\nfactorial = @(n) recur(@(f, k) iif(k == 0, 1, ...\r\n                                   true,   @() k * f(f, k-1)), n);\r\narrayfun(factorial, 1:7)\r\n\r\n%%\r\n% A number to an integer power has a nearly identical form. Here's \r\n% |4.^(0:5)|.\r\n\r\npow = @(x, n) recur(@(f, k) iif(k == 0, 1, ...\r\n                                true,   @() x * f(f, k-1)), n);\r\narrayfun(@(n) pow(4, n), 0:5)\r\n\r\n%%\r\n% That was a big step for anonymous functions, using both recursion and an\r\n% inline conditional together with ease. Like |map| and |iif|, |recur|, \r\n% looks strange at first, but once it's been seen, it's hard to forget how \r\n% it works (just make one of the inputs a function handle and pass it to \r\n% itself). And recursion doesn't have to stop at interesting mathematical \r\n% sequences of numbers. For instance, in the next part, we'll use this to \r\n% implement loops in, but first, we'll need a some helper functions and a\r\n% good way to execute multiple statements in an anonymous function.\r\n\r\n%% Helpers\r\n% These little functions are useful in many circumstances, and we're going\r\n% to need |curly| frequently.\r\n\r\nparen = @(x, varargin) x(varargin{:});\r\ncurly = @(x, varargin) x{varargin{:}};\r\n\r\n%%\r\n% They allow us to write |x(3, 4)| as |paren(x, 3, 4)| and similarly for \r\n% curly braces. That is, now we can think of parentheses and curly braces \r\n% as functions! At first this might not seem useful. However, imagine \r\n% writing a function to return the width and height of the screen. The data\r\n% we need is available from this call:\r\n\r\nget(0, 'ScreenSize')\r\n\r\n%%\r\n% However, we don't need those preceeding ones. We could save the output to\r\n% a variable, say |x|, and then access x(3:4), but if we need this in an\r\n% anonymous function, we can't save to a variable. How do we access just\r\n% elements 3 and 4? There are numerous ways, but |paren| and |curly| are\r\n% similar to constructs found in other languages and are easy to use, so\r\n% we'll use those here.\r\n%\r\n% Now we can write our |screen_size| function to return just the data we\r\n% want.\r\n\r\nscreen_size = @() paren(get(0, 'ScreenSize'), 3:4);\r\n\r\nscreen_size()\r\n\r\n%%\r\n% While on the subject, note that we can actually use any number of\r\n% indices or even ':'.\r\n\r\nmagic(3)\r\nparen(magic(3), 1:2, 2:3)\r\nparen(magic(3), 1:2, :)\r\n\r\n%%\r\n% We do the same with the curly braces. Here, the regular expression \r\n% pattern will match both 'rain' and 'Spain', but we'll only select the \r\n% second match.\r\n\r\nspain = curly(regexp('The rain in Spain....', '\\s(\\S+ain)', 'tokens'), 2)\r\n\r\n%%\r\n% (Click for <https:\/\/www.mathworks.com\/help\/matlab\/ref\/regexp.html Regexp \r\n% help>.)\r\n\r\n%%\r\n% It also works with ':' (note that the single quotes are required).\r\n\r\n[a, b] = curly({'the_letter_a', 'the_letter_b'}, ':')\r\n\r\n%% Executing Multiple Statements\r\n%\r\n% With |curly| in place, let's examine something a little different.\r\n% Consider the following:\r\n\r\ndo_three_things = @() {fprintf('This is the first thing.\\n'), ...\r\n                       fprintf('This is the second thing.\\n'), ...\r\n                       max(eig(magic(3)))};\r\n                   \r\ndo_three_things()\r\n\r\n%%\r\n% We've executed three statements on a single line. All of the outputs are\r\n% stored in the cell array, so we have three elements in the cell array.\r\n% The first two outputs are actually garbage as far as we're concerned\r\n% (they're just the outputs from |fprintf|, which is the number of \r\n% bytes written, which we don't care about at all). The last output is from\r\n% |max(eig(magic(3)))|; That is, the biggest eigenvalue of |magic(3)| is \r\n% exactly 15. Let's say we just wanted that final value, the eigenvalue.\r\n% It's the third element of the cell array, so we can grab it with |curly|.\r\n\r\ndo_three_things = @() curly({fprintf('This is the first thing.\\n'), ...\r\n                             fprintf('This is the second thing.\\n'), ...\r\n                             max(eig(magic(3)))}, 3);\r\n                   \r\ndo_three_things()\r\n\r\n%%\r\n% For a more complex example, let's say we want to write a function to:\r\n% \r\n% # Create a small figure in the middle of the screen\r\n% # Plot some random points\r\n% # Return the handles of the figure and the plot\r\n%\r\n% Then by storing all of the outputs in a cell array and using |curly| to\r\n% access the outputs we care about, we can make a multi-line function with\r\n% multiple outputs, all in a simple anonymous function.\r\n\r\ndots = @() curly({...\r\n    figure('Position', [0.5*screen_size() - [100 50], 200, 100], ...\r\n           'MenuBar',  'none'), ...                % Position the figure\r\n    plot(randn(1, 100), randn(1, 100), '.')}, ...  % Plot random points\r\n    ':');                                          % Return everything\r\n\r\n[h_figure, h_dots] = dots()\r\n\r\n%%\r\n% (As a quick aside, note that if a statement doesn't return anything, we\r\n% can't put it in a cell array, and so we can't use it this way. There are\r\n% ways around this, discussed \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/39735-functional-programming-constructs here>.)\r\n\r\n%% To Be Continued\r\n% \r\n% Today, we've come a long way, from a simple condition through recursion\r\n% and executing multiple statements. Here's a roundup of the functions so \r\n% far.\r\n\r\nmap     = @(val, fcns) cellfun(@(f) f(val{:}), fcns);\r\nmapc    = @(val, fcns) cellfun(@(f) f(val{:}), fcns, 'UniformOutput', 0);\r\niif     = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();\r\nrecur   = @(f, varargin) f(f, varargin{:});\r\nparen   = @(x, varargin) x(varargin{:});\r\ncurly   = @(x, varargin) x{varargin{:}};\r\n\r\n%%\r\n% These can also be found \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/39735-functional-programming-constructs here>,\r\n% implemented as regular MATLAB functions that can be kept on the path.\r\n\r\n%%\r\n% Next time, we'll look at loops. Until then, have you worked with \r\n% functions such as |paren| or |curly|? How else are people implementing \r\n% these or similar operations? Let us know <https:\/\/blogs.mathworks.com\/loren\/?p=611#respond here>.\r\n\r\n##### SOURCE END ##### 785282659a42421c916b8b165e146cdb\r\n-->","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2013\/functional_programming_techniques_2_01.png\" onError=\"this.style.display ='none';\" \/><\/div><!--introduction--><p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/225094\">Tucker McClure<\/a> is an Application Engineer with The MathWorks. He spends his time helping our customers accelerate their work with the right tools and problem-solving techniques. Today, he'll be discussing how \"functional programming\" can help create brief and powerful MATLAB code.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2013\/01\/24\/introduction-to-functional-programming-with-anonymous-functions-part-2\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[3,54],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/611"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=611"}],"version-history":[{"count":13,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/611\/revisions"}],"predecessor-version":[{"id":633,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/611\/revisions\/633"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=611"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=611"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=611"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}