{"id":1786,"date":"2015-04-25T13:13:45","date_gmt":"2015-04-25T19:13:45","guid":{"rendered":"http:\/\/jamesonquave.com\/blog\/?p=1786"},"modified":"2015-04-26T14:05:19","modified_gmt":"2015-04-26T20:05:19","slug":"functional-programming-in-swift","status":"publish","type":"post","link":"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/","title":{"rendered":"Functional Programming in Swift"},"content":{"rendered":"<h1 id=\"thoughts-on-functional-programming-in-swift\">Thoughts on Functional Programming in Swift<\/h1>\n<p>Like most of you, I have to use Objective-C at my day job. I could only craft my Swift skills at night. Swift is not a purely functional language. It can be use imperatively because all frameworks from Apple are written in Objective-C at the time of writing. However, it is also functional, learning from modern languages like Haskell, F#, etc. At the beginning when reading Swift blogs and tutorials, many people talked about terms like functors and monads, those sounded alien-like to me. I started to learn Haskell to understand what they were talking about. I&#8217;m not an expert, and still learning functional programming and Swift, but I wanted to share what I\u2019ve learned so far. Hopefully it will save you some troubles to get into the functional programming world.<\/p>\n<h1 id=\"key-concepts\">Key Concepts<\/h1>\n<h2 id=\"higher-order-functions\">Higher-order functions<\/h2>\n<p>One key concept of functional programming is higher-order functions. According to <a href=\"http:\/\/en.wikipedia.org\/wiki\/Higher-order_function\">Wikipedia<\/a>, a higher-order function:<\/p>\n<ul>\n<li>takes one or more functions as an input<\/li>\n<li>outputs a function<\/li>\n<\/ul>\n<p>In Swift, functions are first-class citizens, like structs and classes, as we can see in the following example:<\/p>\n<pre><code class=\"lang-swift\"><div id=\"highlighter_110583\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"keyword\">let<\/code> <code class=\"plain\">addFive = { $0 + 5 }<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"plain\">addFive(7) <\/code><code class=\"comments\">\/\/ Output: 12<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>We define a function as an inline closure, and then assign it to an inline closure. Swift provides shorthand argument to it. Instead of by name, we can refer to the arguments by number, $0, $1 and so on.<\/p>\n<pre><code class=\"lang-swift\"><div id=\"highlighter_786854\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"keyword\">func<\/code> <code class=\"plain\">addThreeAfter(f: <\/code><code class=\"color2\">Int<\/code> <code class=\"plain\">-&gt; <\/code><code class=\"color2\">Int<\/code><code class=\"plain\">) -&gt; <\/code><code class=\"color1\">Int<\/code> <code class=\"plain\">-&gt; <\/code><code class=\"color1\">Int<\/code> <code class=\"plain\">{<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">return<\/code> <code class=\"plain\">{ f($0) + 3 }<\/code><\/div><div class=\"line number3 index2 alt2\"><code class=\"plain\">}<\/code><\/div><div class=\"line number4 index3 alt1\"><code class=\"keyword\">let<\/code> <code class=\"plain\">addEight = addThreeAfter(addFive)<\/code><\/div><div class=\"line number5 index4 alt2\"><code class=\"plain\">addEight(7) <\/code><code class=\"comments\">\/\/ Output: 15<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>The argument type <code>Int -&gt; Int<\/code> means it is a function that takes an Int as an argument, and returns an Int. If a function requires more than one arguments, for example, it has two Int argument, we can define the type as <code>(Int, Int) -&gt; Int<\/code>.<\/p>\n<p>The return type of <code>addThreeAfter<\/code> is also a function. It equivalents to <code>func addThreeAfter(f: Int -&gt; Int) -&gt; (Int -&gt; Int)<\/code>.<\/p>\n<pre><code class=\"lang-swift\"><div id=\"highlighter_140438\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"plain\">[addFive, addEight].<\/code><code class=\"functions\">map<\/code> <code class=\"plain\">{ $0(7) } <\/code><code class=\"comments\">\/\/ Output: [12 15]<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p><code>map<\/code> is a special function for container type, such as Array, Optional. It unwraps values from the container type, then applies a transform for each, and wraps them again. We use <code>map<\/code> here to pass 7 as an argument to each function in the array, and wraps the results into a new array.<\/p>\n<p>In summary, we can assign functions to variables, store them in data structures, pass them as arguments to other functions, and even return them as the values from other functions.<\/p>\n<h2 id=\"pure-functions\">Pure functions<\/h2>\n<p>A function is called a pure function if it has no observable side effects. But what the heck is side effect?<\/p>\n<blockquote>\n<p>A function or expression is said to have a side effect if, in addition to returning a value, it also modifies some state or has an observable interaction with calling functions or the outside world.<br \/>\n&#8212; from <a href=\"http:\/\/en.wikipedia.org\/wiki\/Side_effect_(computer_science)\">Wikipedia<\/a><\/p>\n<\/blockquote>\n<p>The two functions <code>addFive<\/code> and <code>addEight<\/code> are pure functions. They don\u2019t modify the input value, or change any global state. In the example below, <code>addFive2<\/code> modifies the input, so it is not a pure function.<\/p>\n<pre><code class=\"lang-swift\"><div id=\"highlighter_235316\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"keyword\">func<\/code> <code class=\"plain\">addFive2(<\/code><code class=\"keyword\">inout<\/code> <code class=\"plain\">a: <\/code><code class=\"color1\">Int<\/code><code class=\"plain\">) -&gt; <\/code><code class=\"color1\">Int<\/code> <code class=\"plain\">{<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">a += 5<\/code><\/div><div class=\"line number3 index2 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">return<\/code> <code class=\"plain\">a<\/code><\/div><div class=\"line number4 index3 alt1\"><code class=\"plain\">}<\/code><\/div><div class=\"line number5 index4 alt2\"><code class=\"keyword\">var<\/code> <code class=\"plain\">a = 7<\/code><\/div><div class=\"line number6 index5 alt1\"><code class=\"plain\">addFive2(&amp;a)<\/code><\/div><div class=\"line number7 index6 alt2\"><code class=\"plain\">a <\/code><code class=\"comments\">\/\/ Output: 12<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>Functions that access or modify a database, the local file system, or printing strings to the screen are also considered impure. Because they modify the state of the database records, file system, and display buffers respectively. Sometimes side effects are desirable. Without side effects, we could not interact with the program.<\/p>\n<p>Haskell introduces types like IO to separate pure and impure layers. But in Swift, we don&#8217;t need to worry too much about this separation. We could still use Cocoa APIs as usual. But, I strongly encourage the use of pure functions whenever possible. With pure functions, the code is more predictable. A pure function will always return the same value if given the same input. It&#8217;s easy to test, too. We don&#8217;t need to mock a data structure to satisfy its internal state requirements to test a function.<\/p>\n<h1 id=\"imperative-functional-programming\">Imperative &amp; Functional Programming<\/h1>\n<p>All above are very theoretical. You may want to know how functional programming with help us solve problems in a better, clearer, or less error-prone way. What are the benefits we could gain from it?<\/p>\n<p>First, you need to understand that we could do almost anything in imperative programming, and functional programming does not extend the possibilities of what we could do. <\/p>\n<p>Second, if you come from the imperative programming world, some functional code is harder to understand at first, especially those with custom operators. It is not because functional programming is hard and obscure, but it\u2019s because our mindsets are trained from years of imperative programming practices.<\/p>\n<p>Take a look at this example of imperative code, which we can rewrite as functional code. These two do exactly the same things.<\/p>\n<pre><code class=\"lang-swift\"><div id=\"highlighter_781785\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"comments\">\/\/ Imperative<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"keyword\">var<\/code> <code class=\"plain\">source = [1, 3, 5, 7, 9]<\/code><\/div><div class=\"line number3 index2 alt2\"><code class=\"keyword\">var<\/code> <code class=\"plain\">result = [<\/code><code class=\"color1\">Int<\/code><code class=\"plain\">]()<\/code><\/div><div class=\"line number4 index3 alt1\"><code class=\"keyword\">for<\/code> <code class=\"plain\">i <\/code><code class=\"keyword\">in<\/code> <code class=\"plain\">source {<\/code><\/div><div class=\"line number5 index4 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">let<\/code> <code class=\"plain\">timesTwo = i * 2<\/code><\/div><div class=\"line number6 index5 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">if<\/code> <code class=\"plain\">timesTwo &gt; 5 &amp;&amp; timesTwo &lt; 15 {<\/code><\/div><div class=\"line number7 index6 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">result.append(timesTwo)<\/code><\/div><div class=\"line number8 index7 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">}<\/code><\/div><div class=\"line number9 index8 alt2\"><code class=\"plain\">}<\/code><\/div><div class=\"line number10 index9 alt1\"><code class=\"plain\">result <\/code><code class=\"comments\">\/\/ Output: [6, 10, 14]<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<pre><code class=\"lang-swift\"><div id=\"highlighter_605693\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"comments\">\/\/ Functional<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"keyword\">let<\/code> <code class=\"plain\">result2 = source.<\/code><code class=\"functions\">map<\/code> <code class=\"plain\">{ $0 * 2 }<\/code><\/div><div class=\"line number3 index2 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">.<\/code><code class=\"functions\">filter<\/code> <code class=\"plain\">{ $0 &gt; 5 &amp;&amp; $0 &lt; 15 }<\/code><\/div><div class=\"line number4 index3 alt1\"><code class=\"plain\">result2 <\/code><code class=\"comments\">\/\/ Output: [6, 10, 14]<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>It is arguable which one is clearer. But from this simple example you can see the main difference between imperative and functional programming. In imperative programming, we instruct the computer <em>how<\/em> to do something:<\/p>\n<ol>\n<li>Iterate through <code>source<\/code><\/li>\n<li>Get the result from the element, and multiply by 2<\/li>\n<li>Compare it with 5 and 15<\/li>\n<li>If it is bigger than 5 and less than 15, put it into <code>result<\/code><\/li>\n<\/ol>\n<p>However, in functional programming, we describe <em>what<\/em> to do:<\/p>\n<ol>\n<li>Transform each element in <code>source<\/code> to itself multiplied by 2<\/li>\n<li>Only select the ones with value bigger than 5 and less than 15<\/li>\n<\/ol>\n<p>I&#8217;m not going to persuade you functional programming is better. It&#8217;s your personal preference. After all, good code is all about writing code that:<\/p>\n<ol>\n<li>Works as intended<\/li>\n<li>Is clear to you and your team<\/li>\n<\/ol>\n<h1 id=\"an-example-reverse-polish-notation-calculator\">An Example: Reverse Polish Notation Calculator<\/h1>\n<p>I like Swift and functional programming, because it enables me to solve a problem in a different perspective. There is usually more than one way to solve a problem. Exploring a better solution helps us grow to become good developers.<\/p>\n<p>Let me show you a functional example. It is a calculator for algebraic expressions of reverse polish notation, or RPN in short. (It is a Swift implementation of the Haskell example in <a href=\"http:\/\/www.amazon.com\/gp\/product\/1593272839\/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1593272839&amp;linkCode=as2&amp;tag=jamequav-20&amp;linkId=JERXKKH7GUAGLKMU\">Learn You a Haskell for Great Good<\/a>.)<\/p>\n<p>A RPN expression of (3 + 5) <em> 2 is 3 5 + 2 <\/em>. You may think of this as a stack of numbers. We go through the RPN expression from left to right. When encountering a number, we push it onto the stack. When we encounter an operator, we pop two numbers from the stack, use the operator with those two numbers, and then push the result back onto the stack. When reaching the end of the expression, the only one number left on the stack is the result (assuming the RPN expression is valid). For more explanation about RPN, please check on <a href=\"http:\/\/en.wikipedia.org\/wiki\/Reverse_Polish_notation\">Wikipedia<\/a>.<\/p>\n<p>We want a function that returns the result for an RPN expression.<\/p>\n<pre><code class=\"lang-swift\"><div id=\"highlighter_851986\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"keyword\">func<\/code> <code class=\"plain\">solveRPN(expression: <\/code><code class=\"color1\">String<\/code><code class=\"plain\">) -&gt; <\/code><code class=\"color1\">Double<\/code> <code class=\"plain\">{<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"comments\">\/\/ Process the expression and return the result<\/code><\/div><div class=\"line number3 index2 alt2\"><code class=\"plain\">}<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>Given a RPN expression String &#8220;3 5 + 2 *&#8221;, first we need to transform it into an array of elements that we can process. There are two kind of elements, operand and operator. The Enum data type in Swift comes in handy for defining the element. We name it <code>RPNElement<\/code>.<\/p>\n<pre><code class=\"lang-swift\"><div id=\"highlighter_298677\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"keyword\">enum<\/code> <code class=\"color2\">RPNElement<\/code> <code class=\"plain\">{<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">case<\/code> <code class=\"color2\">Operand<\/code><code class=\"plain\">(<\/code><code class=\"color1\">Double<\/code><code class=\"plain\">)<\/code><\/div><div class=\"line number3 index2 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">case<\/code> <code class=\"color2\">Operator<\/code><code class=\"plain\">(<\/code><code class=\"color1\">String<\/code><code class=\"plain\">, (<\/code><code class=\"color2\">Double<\/code><code class=\"plain\">, <\/code><code class=\"color2\">Double<\/code><code class=\"plain\">) -&gt; <\/code><code class=\"color1\">Double<\/code><code class=\"plain\">)<\/code><\/div><div class=\"line number4 index3 alt1\"><code class=\"plain\">}<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>Next, we split the expression into an array of Strings, then <code>map<\/code> it into an RPNElement array.<\/p>\n<pre><code class=\"lang-swift\"><div id=\"highlighter_935647\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"plain\">extension <\/code><code class=\"color1\">String<\/code> <code class=\"plain\">{<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">func<\/code> <code class=\"plain\">toRPNElement() -&gt; <\/code><code class=\"color2\">RPNElement<\/code> <code class=\"plain\">{<\/code><\/div><div class=\"line number3 index2 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">switch<\/code> <code class=\"keyword\">self<\/code> <code class=\"plain\">{<\/code><\/div><div class=\"line number4 index3 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">case<\/code> <code class=\"string\">\"*\"<\/code><code class=\"plain\">: <\/code><code class=\"keyword\">return<\/code> <code class=\"plain\">.<\/code><code class=\"color2\">Operator<\/code><code class=\"plain\">(<\/code><code class=\"keyword\">self<\/code><code class=\"plain\">, { $0 * $1 })<\/code><\/div><div class=\"line number5 index4 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">case<\/code> <code class=\"string\">\"+\"<\/code><code class=\"plain\">: <\/code><code class=\"keyword\">return<\/code> <code class=\"plain\">.<\/code><code class=\"color2\">Operator<\/code><code class=\"plain\">(<\/code><code class=\"keyword\">self<\/code><code class=\"plain\">, { $0 + $1 })<\/code><\/div><div class=\"line number6 index5 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">case<\/code> <code class=\"string\">\"-\"<\/code><code class=\"plain\">: <\/code><code class=\"keyword\">return<\/code> <code class=\"plain\">.<\/code><code class=\"color2\">Operator<\/code><code class=\"plain\">(<\/code><code class=\"keyword\">self<\/code><code class=\"plain\">, { $0 - $1 })<\/code><\/div><div class=\"line number7 index6 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">default<\/code><code class=\"plain\">: <\/code><code class=\"keyword\">return<\/code> <code class=\"plain\">.<\/code><code class=\"color2\">Operand<\/code><code class=\"plain\">(<\/code><code class=\"color2\">Double<\/code><code class=\"plain\">(<\/code><code class=\"keyword\">self<\/code><code class=\"plain\">.toInt()!))<\/code><\/div><div class=\"line number8 index7 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">}<\/code><\/div><div class=\"line number9 index8 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">}<\/code><\/div><div class=\"line number10 index9 alt1\"><code class=\"plain\">}<\/code><\/div><div class=\"line number11 index10 alt2\"><code class=\"keyword\">func<\/code> <code class=\"plain\">stringToRPNElement(s: <\/code><code class=\"color2\">String<\/code><code class=\"plain\">) -&gt; <\/code><code class=\"color2\">RPNElement<\/code> <code class=\"plain\">{<\/code><\/div><div class=\"line number12 index11 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">return<\/code> <code class=\"plain\">s.toRPNElement()<\/code><\/div><div class=\"line number13 index12 alt2\"><code class=\"plain\">}<\/code><\/div><div class=\"line number14 index13 alt1\"><code class=\"keyword\">func<\/code> <code class=\"plain\">solveRPN(expression: <\/code><code class=\"color2\">String<\/code><code class=\"plain\">) -&gt; <\/code><code class=\"color1\">Double<\/code> <code class=\"plain\">{<\/code><\/div><div class=\"line number15 index14 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">let<\/code> <code class=\"plain\">elements = expression.componentsSeparatedByString(<\/code><code class=\"string\">\" \"<\/code><code class=\"plain\">).<\/code><code class=\"functions\">map<\/code><code class=\"plain\">(stringToRPNElement)<\/code><\/div><div class=\"line number16 index15 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"comments\">\/\/ Further process <\/code><\/div><div class=\"line number17 index16 alt2\"><code class=\"plain\">}<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>Next, we will go through the array and process it according to how RPN works, as I described earlier. We <code>reduce<\/code> the array into a Double array. Assuming the expression is valid, the Double array should only contain one element. It will be the result we want.<\/p>\n<pre><code class=\"lang-swift\"><div id=\"highlighter_4272\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"keyword\">func<\/code> <code class=\"plain\">solveRPN(expression: <\/code><code class=\"color1\">String<\/code><code class=\"plain\">) -&gt; <\/code><code class=\"color1\">Double<\/code> <code class=\"plain\">{<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">let<\/code> <code class=\"plain\">elements = expression.componentsSeparatedByString(<\/code><code class=\"string\">\" \"<\/code><code class=\"plain\">).<\/code><code class=\"functions\">map<\/code><code class=\"plain\">(stringToRPNElement)<\/code><\/div><div class=\"line number3 index2 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">let<\/code> <code class=\"plain\">results = elements.reduce([]) { (acc: [<\/code><code class=\"color2\">Double<\/code><code class=\"plain\">], e: <\/code><code class=\"color2\">RPNElement<\/code><code class=\"plain\">) -&gt; [<\/code><code class=\"color1\">Double<\/code><code class=\"plain\">]&nbsp; <\/code><code class=\"keyword\">in<\/code><\/div><div class=\"line number4 index3 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">switch<\/code> <code class=\"plain\">e {<\/code><\/div><div class=\"line number5 index4 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">case<\/code> <code class=\"plain\">.<\/code><code class=\"color2\">Operand<\/code><code class=\"plain\">(<\/code><code class=\"keyword\">let<\/code> <code class=\"plain\">operand):<\/code><\/div><div class=\"line number6 index5 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">return<\/code> <code class=\"plain\">[operand] + acc<\/code><\/div><div class=\"line number7 index6 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">case<\/code> <code class=\"plain\">.<\/code><code class=\"color2\">Operator<\/code><code class=\"plain\">(<\/code><code class=\"keyword\">let<\/code> <code class=\"plain\">op, <\/code><code class=\"keyword\">let<\/code> <code class=\"plain\">f):<\/code><\/div><div class=\"line number8 index7 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">let<\/code> <code class=\"plain\">r = f(acc[0], acc[1])<\/code><\/div><div class=\"line number9 index8 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">return<\/code> <code class=\"plain\">[r] + acc[2..&lt;acc.count]<\/code><\/div><div class=\"line number10 index9 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">}<\/code><\/div><div class=\"line number11 index10 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">}<\/code><\/div><div class=\"line number12 index11 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">return<\/code> <code class=\"plain\">results.first ?? 0<\/code><\/div><div class=\"line number13 index12 alt2\"><code class=\"plain\">}<\/code><\/div><div class=\"line number14 index13 alt1\"><code class=\"plain\">solveRPN(<\/code><code class=\"string\">\"3 5 + 2 *\"<\/code><code class=\"plain\">) <\/code><code class=\"comments\">\/\/ Output: 16<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<h1 id=\"where-to-go-from-here-\">Where to Go From Here?<\/h1>\n<p>If you are interested in learning more about functional programming, I highly recommend the following two books:<\/p>\n<ul>\n<li><a href=\"http:\/\/www.amazon.com\/gp\/product\/3000480056\/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=3000480056&amp;linkCode=as2&amp;tag=jamequav-20&amp;linkId=A2LGNJTQX2HSGJRY\">Functional Programming in Swift by Chris Eidhof, Florian Kugler, and Wouter Swierstra<\/a><\/li>\n<li><a href=\"https:\/\/gumroad.com\/l\/maybe-haskell\/\">Maybe Haskell from thoughtbot<\/a><\/li>\n<\/ul>\n<p>Even though the second book is written for Haskell, but the concepts also apply to Optional in Swift as well. Besides, it explains Functor, Applicative, Monad in details.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Thoughts on Functional Programming in Swift Like most of you, I have to use Objective-C at my day job. I could only craft my Swift skills at night. Swift is not a purely functional language. It can be use imperatively because all frameworks from Apple are written in Objective-C at the time of writing. However,&#8230;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_links_to":"","_links_to_target":""},"categories":[50,25,10,32],"tags":[69,34,33],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v19.13 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Functional Programming in Swift - Jameson Quave<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Functional Programming in Swift - Jameson Quave\" \/>\n<meta property=\"og:description\" content=\"Thoughts on Functional Programming in Swift Like most of you, I have to use Objective-C at my day job. I could only craft my Swift skills at night. Swift is not a purely functional language. It can be use imperatively because all frameworks from Apple are written in Objective-C at the time of writing. However,...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/\" \/>\n<meta property=\"og:site_name\" content=\"Jameson Quave\" \/>\n<meta property=\"article:published_time\" content=\"2015-04-25T19:13:45+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2015-04-26T20:05:19+00:00\" \/>\n<meta name=\"author\" content=\"Guanshan Liu\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Guanshan Liu\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/\",\"url\":\"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/\",\"name\":\"Functional Programming in Swift - Jameson Quave\",\"isPartOf\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/#website\"},\"datePublished\":\"2015-04-25T19:13:45+00:00\",\"dateModified\":\"2015-04-26T20:05:19+00:00\",\"author\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/d0ef4e53cd95e21e389aefe6277f0811\"},\"breadcrumb\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jamesonquave.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Functional Programming in Swift\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#website\",\"url\":\"https:\/\/jamesonquave.com\/blog\/\",\"name\":\"Jameson Quave\",\"description\":\"Using computer technology to educate, and improve lives.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jamesonquave.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/d0ef4e53cd95e21e389aefe6277f0811\",\"name\":\"Guanshan Liu\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/8f00053e85112a67cee95968f2f36ab2?s=96&d=retro&r=pg\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/8f00053e85112a67cee95968f2f36ab2?s=96&d=retro&r=pg\",\"caption\":\"Guanshan Liu\"},\"description\":\"Guanshan is an iOS Developer currently working as an iOS Engineer at Alibaba Inc. Before working at Alibaba, Guanshan worked with 2K Games on Civilization Revolution 1 and 2 for iOS. He has a Masters in Software Engineering from the University of York, UK as well as a Bachelors of Engineering in Information Security from Nanjing University of Aeronautics and Astronautics. Find him on twitter, @guanshanliu.\",\"sameAs\":[\"https:\/\/guanshanliu.github.io\"],\"url\":\"https:\/\/jamesonquave.com\/blog\/author\/guanshanliu\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Functional Programming in Swift - Jameson Quave","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/","og_locale":"en_US","og_type":"article","og_title":"Functional Programming in Swift - Jameson Quave","og_description":"Thoughts on Functional Programming in Swift Like most of you, I have to use Objective-C at my day job. I could only craft my Swift skills at night. Swift is not a purely functional language. It can be use imperatively because all frameworks from Apple are written in Objective-C at the time of writing. However,...","og_url":"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/","og_site_name":"Jameson Quave","article_published_time":"2015-04-25T19:13:45+00:00","article_modified_time":"2015-04-26T20:05:19+00:00","author":"Guanshan Liu","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Guanshan Liu","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/","url":"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/","name":"Functional Programming in Swift - Jameson Quave","isPartOf":{"@id":"https:\/\/jamesonquave.com\/blog\/#website"},"datePublished":"2015-04-25T19:13:45+00:00","dateModified":"2015-04-26T20:05:19+00:00","author":{"@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/d0ef4e53cd95e21e389aefe6277f0811"},"breadcrumb":{"@id":"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jamesonquave.com\/blog\/functional-programming-in-swift\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jamesonquave.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Functional Programming in Swift"}]},{"@type":"WebSite","@id":"https:\/\/jamesonquave.com\/blog\/#website","url":"https:\/\/jamesonquave.com\/blog\/","name":"Jameson Quave","description":"Using computer technology to educate, and improve lives.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jamesonquave.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/d0ef4e53cd95e21e389aefe6277f0811","name":"Guanshan Liu","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/8f00053e85112a67cee95968f2f36ab2?s=96&d=retro&r=pg","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/8f00053e85112a67cee95968f2f36ab2?s=96&d=retro&r=pg","caption":"Guanshan Liu"},"description":"Guanshan is an iOS Developer currently working as an iOS Engineer at Alibaba Inc. Before working at Alibaba, Guanshan worked with 2K Games on Civilization Revolution 1 and 2 for iOS. He has a Masters in Software Engineering from the University of York, UK as well as a Bachelors of Engineering in Information Security from Nanjing University of Aeronautics and Astronautics. Find him on twitter, @guanshanliu.","sameAs":["https:\/\/guanshanliu.github.io"],"url":"https:\/\/jamesonquave.com\/blog\/author\/guanshanliu\/"}]}},"_links":{"self":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1786"}],"collection":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/comments?post=1786"}],"version-history":[{"count":7,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1786\/revisions"}],"predecessor-version":[{"id":1793,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1786\/revisions\/1793"}],"wp:attachment":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/media?parent=1786"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/categories?post=1786"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/tags?post=1786"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}