Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Functional Swift - SF

Functional Swift - SF

Presented at the Swift Language User Group

Chris Eidhof | @chriseidhof

September 02, 2014
Tweet

More Decks by Chris Eidhof | @chriseidhof

Other Decks in Technology

Transcript

  1. Functional Swift
    @chriseidhof

    View full-size slide

  2. The Objective-C way
    CIFilter *hueAdjust = [CIFilter filterWithName:@"CIHueAdjust"];
    [hueAdjust setDefaults];
    [hueAdjust setValue: myCIImage forKey: kCIInputImageKey];
    [hueAdjust setValue: @2.094f forKey: kCIInputAngleKey];

    View full-size slide

  3. A Swift Filter
    typealias Filter = CIImage -> CIImage

    View full-size slide

  4. Blur
    func blur(radius: Double) -> Filter {
    return { image in
    let parameters : Parameters =
    [kCIInputRadiusKey: radius, kCIInputImageKey: image]
    let filter = CIFilter(name:"CIGaussianBlur",
    parameters:parameters)
    return filter.outputImage
    }
    }

    View full-size slide

  5. Example
    let url = NSURL(string: "http://tinyurl.com/sfswift");
    let image = CIImage(contentsOfURL: url)
    let blurBy5 = blur(5)
    let blurred = blurBy5(image)

    View full-size slide

  6. Color Generator
    func colorGenerator(color: NSColor) -> Filter {
    return { _ in
    let filter = CIFilter(name:"CIConstantColorGenerator",
    parameters: [kCIInputColorKey: color])
    return filter.outputImage
    }
    }

    View full-size slide

  7. Composite Source Over
    func compositeSourceOver(overlay: CIImage) -> Filter {
    return { image in
    let parameters : Parameters =
    [kCIInputBackgroundImageKey: image,
    kCIInputImageKey: overlay]
    let filter = CIFilter(name:"CISourceOverCompositing",
    parameters: parameters)
    return filter.outputImage.imageByCroppingToRect(image.extent())
    }
    }

    View full-size slide

  8. Color Overlay
    func colorOverlay(color: NSColor) -> Filter {
    return { image in
    let overlay = colorGenerator(color)(image)
    return compositeSourceOver(overlay)(image)
    }
    }

    View full-size slide

  9. Combining everything
    let blurRadius = 5.0
    let overlayColor = NSColor.redColor().colorWithAlphaComponent(0.2)
    let blurredImage = blur(blurRadius)(image)
    let overlaidImage = colorOverlay(overlayColor)(blurredImage)

    View full-size slide

  10. Combining everything, take 2
    let result = colorOverlay(overlayColor)(blur(blurRadius)(image))

    View full-size slide

  11. Filter composition
    func composeFilters(filter1: Filter, filter2: Filter) -> Filter {
    return {img in filter1(filter2(img)) }
    }

    View full-size slide

  12. Using filter composition
    let myFilter1 = composeFilters(blur(blurRadius),
    colorOverlay(overlayColor))
    let result1 = myFilter1(image)

    View full-size slide

  13. Filter composition with an operator
    infix operator |> { associativity left }
    func |> (filter1: Filter, filter2: Filter) -> Filter {
    return {img in filter1(filter2(img))}
    }

    View full-size slide

  14. Using filter composition
    let myFilter2 = blur(blurRadius) |> colorOverlay(overlayColor)
    let result2 = myFilter2(image)

    View full-size slide

  15. Function composition
    func |> (f1: B -> C, f2: A -> B) -> A -> C {
    return {x in f1(f2(x))}
    }

    View full-size slide

  16. Objective-C
    [[NSColor blueColor] setFill]
    CGContextFillRect(context, CGRectMake(0.0,37.5,75.0,75.0))
    [[NSColor redColor] setFill]
    CGContextFillRect(context, CGRectMake(75.0,0.0,150.0,150.0))
    [[NSColor greenColor] setFill]
    CGContextFillEllipseInRect(context, CGRectMake(225.0,37.5,75.0,75.0))

    View full-size slide

  17. Another example

    View full-size slide

  18. Swift
    let blueSquare = square(side: 1).fill(NSColor.blueColor())
    let redSquare = square(side: 2).fill(NSColor.redColor())
    let greenCircle = circle(radius: 1).fill(NSColor.greenColor())
    let example1 = blueSquare ||| redSquare ||| greenCircle

    View full-size slide

  19. Extending
    let example2 = blueSquare |||
    circle(radius: 1).fill(NSColor.cyanColor()) |||
    redSquare |||
    greenCircle

    View full-size slide

  20. A bar graph
    La Plata Blanca Elbert Massive Harvard

    View full-size slide

  21. The data
    let summits = ["Elbert": 440,
    "Massive": 428,
    "Harvard": 421,
    "La Plata": 368,
    "Blanca": 357]
    barGraph(summits.keysAndValues)

    View full-size slide

  22. Drawing a bar graph
    func barGraph(input: [(String,Double)]) -> Diagram {
    let values : [CGFloat] = input.map { CGFloat($0.1) }
    let bars = hcat(normalize(values).map {
    return rect(width: 1, height: 3*x).
    alignBottom()
    })
    let labels = hcat(input.map { x in
    return text(width: 1, height: 0.3, text: x.0).
    alignTop()
    })
    return bars --- labels
    }

    View full-size slide

  23. Primitives
    enum Primitive {
    case Ellipsis
    case Rectangle
    case Text(String)
    }

    View full-size slide

  24. The Diagram type
    enum Diagram {
    case Prim(CGSize, Primitive)
    case Beside(Diagram, Diagram)
    case Below(Diagram, Diagram)
    case Attributed(Attribute, Diagram)
    case Align(Vector2D, Diagram)
    }

    View full-size slide

  25. Drawing
    func draw(context: CGContextRef,
    bounds: CGRect,
    diagram: Diagram) {
    switch diagram {
    case .Prim(let size, .Ellipsis):
    let frame = fit(center, size, bounds)
    CGContextFillEllipseInRect(context, frame)
    case .Prim(let size, .Rectangle):
    let frame = fit(center, size, bounds)
    CGContextFillRect(context, frame)

    View full-size slide

  26. Drawing Text
    case .Prim(let size, .Text(let text)):
    let frame = fit(center, size, bounds)
    let attributes = [NSFontAttributeName:
    NSFont.systemFontOfSize(12)]
    let attributedText = NSAttributedString
    (string: text,
    attributes: attributes)
    attributedText.drawInRect(frame)

    View full-size slide

  27. Drawing Attributes
    case .Attributed(.FillColor(let color), let d):
    CGContextSaveGState(context)
    color.set()
    draw(context, bounds, d)
    CGContextRestoreGState(context)

    View full-size slide

  28. Drawing Combinations
    case .Beside(let l, let r):
    let (lFrame, rFrame) = splitHorizontal(bounds,
    l.size/diagram.size)
    draw(context, lFrame, l)
    draw(context, rFrame, r)
    case .Below(let t, let b):
    let (lFrame, rFrame) = splitVertical(bounds,
    b.size/diagram.size)
    draw(context, lFrame, b)
    draw(context, rFrame, t)

    View full-size slide

  29. Drawing Aligned Diagrams
    case .Align(let vec, let d):
    let diagram = d.diagram()
    let frame = fit(vec, diagram.size, bounds)
    draw(context, frame, diagram)
    }
    }

    View full-size slide

  30. Operators
    infix operator ||| { associativity left }
    func ||| (l: Diagram, r: Diagram) -> Diagram {
    return Diagram.Beside(l, r)
    }
    infix operator --- { associativity left }
    func --- (l: Diagram, r: Diagram) -> Diagram {
    return Diagram.Below(l, r)
    }

    View full-size slide

  31. {
    "stat" : "ok",
    "blogs" : {
    "blog" : [
    {
    "needspassword" : true,
    "id" : 73,
    "name" : "Bloxus test",
    "url" : "http:\/\/remote.bloxus.com\/"
    },
    {
    "id" : 74,
    "name" : "Manila Test",
    "needspassword" : false,
    "url" : "http:\/\/flickrtest1.userland.com\/"
    }
    ]
    }
    }

    View full-size slide

  32. The Blog struct
    struct Blog {
    let id: Int
    let name: String
    let needsPassword : Bool
    let url: NSURL
    }

    View full-size slide

  33. A first version
    func parseBlog(blogDict: [String:AnyObject]) -> Blog? {
    if let id = blogDict["id"] as NSNumber? {
    if let name = blogDict["name"] as NSString? {
    if let needsPassword = blogDict["needspassword"] as NSNumber? {
    if let url = blogDict["url"] as NSString? {
    return Blog(id: id.integerValue,
    name: name,
    needsPassword: needsPassword.boolValue,
    url: NSURL(string: url)
    )
    }
    }
    }
    }
    return nil
    }

    View full-size slide

  34. Parsing a string
    func string(input: [String:AnyObject], key: String) -> String? {
    let result = input[key]
    return result as String?
    }

    View full-size slide

  35. Version 2
    func parseBlog(blogDict: [String:AnyObject]) -> Blog? {
    if let id = blogDict["id"] as NSNumber? {
    if let name = string(blogDict, "name") {
    if let needsPassword = blogDict["needspassword"] as NSNumber? {
    if let url = string(blogDict, "url") {
    return Blog(id: id.integerValue,
    name: name,
    needsPassword: needsPassword.boolValue,
    url: NSURL(string: url)
    )
    }
    }
    }
    }
    return nil
    }

    View full-size slide

  36. Parsing Numbers
    func number(input: [NSObject:AnyObject], key: String) -> NSNumber? {
    let result = input[key]
    return result as NSNumber?
    }
    func int(input: [NSObject:AnyObject], key: String) -> Int? {
    return number(input,key).map { $0.integerValue }
    }
    func bool(input: [NSObject:AnyObject], key: String) -> Bool? {
    return number(input,key).map { $0.boolValue }
    }

    View full-size slide

  37. Version 3
    func parseBlog(blogDict: [String:AnyObject]) -> Blog? {
    if let id = int(blogDict, "id") {
    if let name = string(blogDict, "name") {
    if let needsPassword = bool(blogDict, "needspassword") {
    if let url = string(blogDict, "url") {
    return Blog(id: id,
    name: name,
    needsPassword: needsPassword,
    url: NSURL(string: url)
    )
    }
    }
    }
    }
    return nil
    }

    View full-size slide

  38. Flattening
    func flatten(oa: A?,ob: B?,oc: C?,od: D?) -> (A,B,C,D)? {
    if let a = oa {
    if let b = ob {
    if let c = oc {
    if let d = od {
    return (a,b,c,d)
    }
    }
    }
    }
    return nil
    }

    View full-size slide

  39. Version 4
    func parseBlog(blogData: [String:AnyObject]) -> Blog? {
    let id = int(blogData,"id")
    let name = string(blogData,"name")
    let needsPassword = bool(blogData,"needspassword")
    let url = string(blogData,"url").map { NSURL(string:$0) }
    if let (id, name, needsPassword, url) = flatten(id, name, needsPassword, url) {
    return Blog(id: id, name: name, needsPassword: needsPassword, url: url)
    }
    return nil
    }

    View full-size slide

  40. Removing the if-statement
    func apply(l: ((A,B,C,D) -> R)?, r: (A,B,C,D)?) -> R? {
    if let l1 = l {
    if let r1 = r {
    return l1(r1)
    }
    }
    return nil
    }

    View full-size slide

  41. Version 5
    func parse(blogData: [String:AnyObject]) -> Blog? {
    let id = int(blogData,"id")
    let name = string(blogData,"name")
    let needsPassword = bool(blogData,"needspassword")
    let url = string(blogData,"url").map { NSURL(string:$0) }
    let makeBlog = { Blog(id: $0, name: $1, needsPassword: $2, url: $3) }
    return apply(makeBlog, flatten(id, name, needsPassword, url))
    }

    View full-size slide

  42. Apply, but simpler
    func apply(l: (A -> R)?, r: A?) -> R? {
    if let l1 = l {
    if let r1 = r {
    return l1(r1)
    }
    }
    return nil
    }

    View full-size slide

  43. Currying
    func curry(f: (A,B,C,D) -> R) -> A -> B -> C -> D -> R {
    return { a in { b in { c in { d in f(a,b,c,d) } } } }
    }

    View full-size slide

  44. Currying by example
    // Has type: (Int, String, Bool, NSURL) -> Blog
    let blog = { Blog(id: $0, name: $1, needsPassword: $2, url: $3) }
    // Has type: Int -> (String -> (Bool -> (NSURL -> Blog)))
    let makeBlog = curry(blog)
    // Or: Int -> String -> Bool -> NSURL -> Blog
    let makeBlog = curry(blog)

    View full-size slide

  45. Currying some more
    // Has type: Int -> String -> Bool -> NSURL -> Blog
    let makeBlog = curry(blog)
    // Has type: Int?
    let id = int(blogData, "id")
    // Has type: (String -> Bool -> NSURL -> Blog)?
    let step1 = apply(makeBlog,id)

    View full-size slide

  46. Currying some more
    // Has type: (String -> Bool -> NSURL -> Blog)?
    let step1 = apply(makeBlog,id)
    // Has type: String?
    let name = string(blogData,"name")
    // Has type: (Bool -> NSURL -> Blog)?
    let step2 = apply(step1,name)

    View full-size slide

  47. Version 6
    func parse(blogData: [String:AnyObject]) -> Blog? {
    let id = int(blogData,"id")
    let name = string(blogData,"name")
    let needsPassword = bool(blogData,"needspassword")
    let url = string(blogData,"url").map { NSURL(string:$0) }
    let makeBlog = curry { Blog(id: $0, name: $1, needsPassword: $2, url: $3) }
    return apply(apply(apply(apply(makeBlog, id), name), needsPassword), url)
    }

    View full-size slide

  48. Apply as an operator
    infix operator <*> { associativity left precedence 150 }
    func <*>(l: (A -> B)?, r: A?) -> B? {
    if let l1 = l {
    if let r1 = r {
    return l1(r1)
    }
    }
    return nil
    }

    View full-size slide

  49. Version 7
    func parse(blogData: [String:AnyObject]) -> Blog? {
    let id = int(blogData,"id")
    let name = string(blogData,"name")
    let needsPassword = bool(blogData,"needspassword")
    let url = string(blogData,"url").map { NSURL(string:$0) }
    let makeBlog = curry { Blog(id: $0, name: $1, needsPassword: $2, url: $3) }
    return makeBlog <*> id <*> name <*> needsPassword <*> url
    }

    View full-size slide

  50. Flashback
    func parseBlog(blogDict: [String:AnyObject]) -> Blog? {
    if let id = blogDict["id"] as NSNumber? {
    if let name = blogDict["name"] as NSString? {
    if let needsPassword = blogDict["needspassword"] as NSNumber? {
    if let url = blogDict["url"] as NSString? {
    return Blog(id: id.integerValue,
    name: name,
    needsPassword: needsPassword.boolValue,
    url: NSURL(string: url)
    )
    }
    }
    }
    }
    return nil
    }

    View full-size slide

  51. Version 8
    func parse(blogData: [String:AnyObject]) -> Blog? {
    let makeBlog = curry { Blog(id: $0, name: $1,
    needsPassword: $2, url: $3) }
    return makeBlog <*> int(blogData,"id")
    <*> string(blogData,"name")
    <*> bool(blogData,"needspassword")
    <*> string(blogData,"url").map {
    NSURL(string:$0)
    }
    }

    View full-size slide

  52. https://speakerdeck.com/chriseidhof/

    View full-size slide

  53. By Chris Eidhof, Florian Kugler and Wouter Swierstra

    View full-size slide

  54. @chriseidhof

    View full-size slide