Created
September 16, 2015 15:19
-
-
Save jamesnvc/81a6e6d1f770cd61d620 to your computer and use it in GitHub Desktop.
Intro to functional programming
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 | |
func makeIncr() -> (Int -> Int) { | |
var x = 0 | |
return { y in x += y; return x } | |
} | |
let inc1 = makeIncr() | |
inc1(1) | |
inc1(1) | |
inc1(2) | |
let inc2 = makeIncr() | |
inc2(1) | |
inc1(1) | |
inc2(3) | |
func maxTail(lst: [Int], biggest: Int = Int.min) -> Int { | |
if lst.count == 0 { return biggest } | |
let next = lst.first! | |
let nextBiggest = next > biggest ? next : biggest | |
return maxTail(Array(lst[1..<lst.count]), biggest: nextBiggest) | |
} | |
func max(lst: [Int]) -> Int { | |
// base case | |
if lst.count == 0 { return Int.min } | |
// recursive | |
let head = lst.first! | |
let restMax = max(Array(lst[1..<lst.count])) | |
return head > restMax ? head : restMax | |
} | |
max([1,2,3,4,5]) | |
max([5,4,3,2,1]) | |
max([10, 100, -7, 99, 8]) | |
func take(n: Int, list: Array<Int>) -> Array<Int> { | |
if n == 0 { return [] } // base case | |
// recursive case | |
return [list.first!] + take(n - 1, Array(list[1..<list.count])) | |
} | |
take(3, [1,2,3,4,5]) | |
take(1, [1,3,4,5,6]) | |
take(0, [1,2]) | |
let data = [1,2,3,4,5] | |
let foo = data.map({ x in x + 1 }).filter({ $0 % 2 == 0}).reduce(0, combine: +) | |
var bar = 0 | |
for x in data { | |
let y = x + 1 | |
if y % 2 == 0 { | |
bar += y | |
} | |
} | |
let words = ["foo", "bar", "baz", "foobar"] | |
let totalLength = words.reduce(0, combine: { (count: Int, word: String) -> Int in | |
count + word.lengthOfBytesUsingEncoding(0) | |
}) | |
totalLength | |
let keys = ["foo", "bar", "baz"] | |
let vals = [1,2,3] | |
let dict = Array(zip(keys, vals)).map({ z in (z.0 + "-key", z.1) }).reduce([:], combine: { (dict: [String:Int], tuple: (String,Int)) -> [String:Int] in | |
var d = dict; d[tuple.0] = tuple.1; return d } ) | |
dict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment