Created
September 7, 2015 22:58
-
-
Save jpcarreira/0a294a43494de8afc4af to your computer and use it in GitHub Desktop.
Functional programming using Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
var result:Double? | |
var operandStack = Array<Double>() | |
operandStack.append(2) | |
operandStack.append(5) | |
func operate(sender:String) | |
{ | |
switch sender | |
{ | |
case "+": | |
// this forces to write four functions (add, subtract, etc...) | |
// performOperation(add) | |
performOperation( | |
{ | |
(operator1:Double, operator2:Double) in | |
return operator1 + operator2 | |
}) | |
case "-": | |
// due to type inference we can skip the type declaration | |
// and can also remove the return as it knows performOperation returns something | |
performOperation({ | |
(operator1, operator2) in | |
operator2 - operator1 | |
}) | |
case "*": | |
// shortening further the syntax by using argument notation | |
performOperation({ | |
$0 * $1 | |
}) | |
case "/": | |
// being the last argument we can even put the {} after the function | |
// performOperation(){$1 / $0} | |
// also being the only argument we can remove the () | |
performOperation{$1 / $0} | |
default: | |
break | |
} | |
} | |
func performOperation(operation: (Double, Double) -> Double) | |
{ | |
result = operation(operandStack.removeLast(), operandStack.removeLast()) | |
print("The result is \(result!)") | |
} | |
// Bad use of functional programming! We need repeat all the code!! | |
// A better use is to apply the functions directly, as shown in the switch statement | |
func multiply(operator1:Double, operator2:Double) -> Double | |
{ | |
return operator1 * operator2 | |
} | |
func divide(operator1:Double, operator2:Double) -> Double | |
{ | |
return operator2 / operator2 | |
} | |
func add(operator1:Double, operator2:Double) -> Double | |
{ | |
return operator1 + operator2 | |
} | |
func subtract(operator1:Double, operator2:Double) -> Double | |
{ | |
return operator2 - operator1 | |
} | |
operate("*") | |
//operate("/") | |
//operate("+") | |
//operate("-") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment