Skip to content

Instantly share code, notes, and snippets.

@jamesnvc
Created November 11, 2015 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesnvc/de1a8855ac7160010a31 to your computer and use it in GitHub Desktop.
Save jamesnvc/de1a8855ac7160010a31 to your computer and use it in GitHub Desktop.
Functional Programming demo
(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))))))
//: 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