Created
July 27, 2015 14:47
-
-
Save jamesnvc/f7eb056998bad41e22c8 to your computer and use it in GitHub Desktop.
Functional programming lecture code
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
// closures | |
func makeIncr() -> (Int -> Int) { | |
var n = 0 | |
return { x in n += x; return n } | |
} | |
let inc1 = makeIncr() | |
let inc2 = makeIncr() | |
println("inc1 +1 \(inc1(1))") | |
println("inc2 +1 \(inc2(1))") | |
println("inc1 +2 \(inc1(2))") | |
println("inc2 +3 \(inc2(3))") | |
// Collection processing | |
struct Shape { | |
let size: Double | |
init(size s: Double) { | |
size = s | |
} | |
} | |
let shapes = [Shape(size: 5), Shape(size: 6), Shape(size: 3.8)] | |
let total = shapes.map({s in s.size}).reduce(0, combine: +) | |
total | |
let total2 = shapes.reduce(0, combine: {acc, s in acc + s.size}) | |
total2 | |
var total3: Double = 0 | |
for s in shapes { | |
total3 += s.size | |
} | |
total3 | |
// Currying | |
func addCurried(x: Int) -> (Int -> Int) { | |
return {y in y + x} | |
} | |
addCurried(3)(4) | |
[1,2,3].map(addCurried(2)) | |
// immutable stack | |
// Annoying boxing until Swift 2 | |
final class Box<T> { | |
let unbox: T | |
init (_ x: T) { self.unbox = x } | |
} | |
enum Stack<Element> : Printable { | |
case Empty | |
// Need to box element because of dumb bug | |
case Vals(Box<Element>, Box<Stack<Element>>) | |
var description : String { | |
switch self { | |
case .Empty: | |
return "⊥" | |
case let .Vals(head, tail): | |
return "\(head.unbox), \(tail.unbox.description)" | |
} | |
} | |
} | |
extension Stack { | |
func push(x: Element) -> Stack<Element> { | |
return .Vals(Box(x), Box(self)) | |
} | |
func pop() -> (Element?, Stack<Element>) { | |
switch self { | |
case .Empty: | |
return (nil, .Empty) | |
case let .Vals(top, boxedRest): | |
return (top.unbox, boxedRest.unbox) | |
} | |
} | |
} | |
let foo: Stack<Int> = .Empty | |
foo.push(3) | |
//println("\(foo)") | |
//println("\(foo.push(3))") | |
//println("\(foo.push(3).push(5).push(8))") | |
let quux = foo.push(3).push(5).push(8) | |
let (top, rest) = quux.pop() | |
println("top = \(top) rest = \(rest) quux = \(quux)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment