Created
November 11, 2015 16:18
-
-
Save jamesnvc/de1a8855ac7160010a31 to your computer and use it in GitHub Desktop.
Functional Programming demo
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
(defn rtake | |
[n lst] | |
(if (= n 0) | |
() | |
(cons (first lst) | |
(rtake (dec n) (rest lst))))) | |
(def my-first (partial rtake 1)) | |
(defn rzip | |
[a b] | |
(if (or (empty? a) (empty? b)) | |
() | |
(cons (list (first a) (first b)) | |
(rzip (rest a) (rest b))))) | |
(defn rmax | |
([lst] (rmax lst -10000)) | |
([lst biggest] | |
(if (empty? lst) | |
biggest | |
(let [cur (first lst)] | |
(rmax (rest lst) | |
(if (> cur biggest) | |
cur | |
biggest)))))) |
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 makeIncrementer() -> (Int -> Int) { | |
var x: Int = 0 | |
return { (step: Int) -> Int in | |
x += step | |
return x | |
} | |
} | |
// x = 8 // Error! | |
let inc1 = makeIncrementer() | |
inc1(1) | |
inc1(1) | |
inc1(3) | |
let inc2 = makeIncrementer() | |
inc2(1) | |
inc1(1) | |
inc2(1) | |
let names = ["Adam", "John", "Jason", "James"] | |
// impertative | |
var totalNameLength = 0 | |
for name in names { | |
if name.hasPrefix("J") { | |
totalNameLength += name.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) | |
} | |
} | |
totalNameLength | |
// functional with higher-order functions | |
let lengths = names.filter({ name in name.hasPrefix("J")} | |
).map({ name in name.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) } | |
).reduce(0, combine: { total, nameLength in total + nameLength}) | |
lengths |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment