SlideShare a Scribd company logo
How to use Functional
Reactive Programming
without Black Magic
let me = Person(name: "Jens Ravens")
@JensRavens
GitHub: JensRavens
nerdgeschoss.de
swift.berlin
A short introduction to
functional programming, the
universe and everything.
In the beginning McIlroy
created the unix pipe. And he
saw it was good.
ls | grep *.jpg | sort
Application Architecture
starting from a blank slate
implement to understand
And I promise not to use the
scary M-word.
me, 12 weeks ago.
How to train
your monad.
–Saunders Mac Lane
All told, a monad is just a monoid in the
category of endofunctors.
“
Monads are just Applicative Functors
“
ls | grep *.jpg | sort
Buy it, use it,
break it, fix it,
Trash it, change it,
mail - upgrade it.
– Daft Punk, Technologic
Buy it;
if error {
//TODO: Handle me!
} else {
use it;
if error {
//TODO: Handle me!
} else {
break it;
if error {
//TODO: Handle me!
ls | grep *.jpg | sort
Monad
something that defines map and bind
The optional Monad
let string: String? = "World"
let greeting = string.map{"Hello ($0)”}
//Hello World
extension Optional {
func bind<U> (f: T->U?) -> U? {
if let result = self.map({f($0)}) {
return result
} else {
return nil
}
}
}
The optional Monad
let string: String? = "World"
let greeting = string.map{"Hello ($0)”}
//Hello World
func greetOrNil(name: String)->String? {
if name == "World" {
return "Hello World"
} else {
return nil
}
}
let greeting2 = string.bind(greetOrNil)
//Hello World
The optional Monad
extension Optional {
func bind<U> (f: T->U?) -> U? {
if let result = self.map({f($0)}) {
return result
} else {
return nil
}
}
}
extension Optional {
func bind<U> (f: T->Optional<U>) -> Optional<U> {
switch self {
case let .Some(value): return f(value)
case .None: return nil
}
}
}
The result Monad
public enum Result<T> {
case Success(Box<T>)
case Error(NSError)
}
The result Monad
public enum Result<T> {
…
public func map<U>(f: T -> U) -> Result<U> {
switch self {
case let .Success(v):
return .Success(Box(f(v.value)))
case let .Error(error): return .Error(error)
}
}
…
}
The result Monad
public enum Result<T> {
…
public func bind<U>(f: T -> Result<U>)
-> Result<U> {
switch self {
case let .Success(v): return f(v.value)
case let .Error(error): return .Error(error)
}
}
…
}
ls | grep *.jpg | sort
Monad
Transform
func parseString(data: NSData) ->
Result<String>
func parseJson(data: NSData) ->
Result<[String: AnyObject]>
func asyncGreeting(name: String,
completion: Result<String>->Void)
public func bind<U>(f:(T, (Result<U>->Void))->Void)
-> (Result<U>->Void)->Void {
return { g in
switch self {
case let .Success(v): f(v.value, g)
case let .Error(error): g(.Error(error))
}
}
}
Interstellar
ls | grep *.jpg | sort
public final class Signal<T> {
private var value: Result<T>?
private var callbacks: [Result<T> -> Void] = []
public func subscribe(f: Result<T> -> Void) {
if let value = value {
f(value)
}
callbacks.append(f)
}
public func update(value: Result<T>) {
self.value = value
self.callbacks.map{$0(value)}
}
}
public func map<U>(f: T -> U) -> Signal<U> {
let signal = Signal<U>()
subscribe { result in
signal.update(result.map(f))
}
return signal
}
public func bind<U>(f: T -> Result<U>) -> Signal<U> {
let signal = Signal<U>()
subscribe { result in
signal.update(result.bind(f))
}
return signal
}
public func bind<U>(f: (T, (Result<U>->Void))->Void)
-> Signal<U> {
let signal = Signal<U>()
subscribe { value in
value.bind(f)(signal.update)
}
return signal
}
pushing instead of pulling
the rise of custom
operators
infix operator >>> { associativity left precedence 160 }
public func >>> <A,B> (left: Signal<A>,
right: A->Result<B>) -> Signal<B> {
return left.bind(right)
}
public func >>> <A,B>(left: Signal<A>,
right: (A, (Result<B>->Void))->Void) -> Signal<B>{
return left.bind(right)
}
public func >>> <A,B> (left: Signal<A>, right: A->B) ->
Signal<B> {
return left.map(right)
}
ls | grep *.jpg | sort
ls | grep *.jpg | sort
ls >>> grep("*.jpg") >>> sort
But what about
Threads?
public final class Thread {
public static func main<T>(a: T, completion:
T->Void) {
dispatch_async(dispatch_get_main_queue())
{
completion(a)
}
}
public static func background<T>(queue:
dispatch_queue_t)(_ a: T, _ completion: T->Void)
{
dispatch_async(queue){
completion(a)
}
}
}
ls >>> Thread.background(queue) >>> grep("*.jpg")
>>> sort >>> Thread.main
Extending UIKit to
support Signals.
var SignalHandle: UInt8 = 0
extension UITextField {
public var textSignal: Signal<String> {
let signal: Signal<String>
if let handle = objc_getAssociatedObject(self,
&SignalHandle) as? Signal<String> {
signal = handle
} else {
signal = Signal("")
NSNotificationCenter.defaultCenter().addObserver(self,
selector: Selector("textChanged:"), name:
UITextFieldTextDidChangeNotification, object: self)
objc_setAssociatedObject(self, &SignalHandle,
signal,
objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
return signal
}
public func textChanged(notification: NSNotification) {
textSignal.update(.Success(Box(self.text)))
}
}
If it’s variable, it qualifies
as a Signal.
ReactiveKitten
It’s about gifs. And cats.
And gifs of cats.
userTyping >>> createURL >>> loadRequest
>>> parseData >>> mainThread >>>
displayCats
The transform, the cat
and you.
import Interstellar
private func request(path: String, completion: Result<NSData>->Void)
{
let url = NSURL(string: baseURL.stringByAppendingString(path))!
let request = NSURLRequest(URL: url)
session.dataTaskWithRequest(request){ data, response, error in
if error != nil {
completion(.Error(error))
} else if let response = response as? NSHTTPURLResponse {
if response.statusCode >= 200 && response.statusCode<300 {
completion(.Success(Box(data)))
} else {
completion(.Error(NSError(domain: "Networking", code:
response.statusCode, userInfo: nil)))
}
} else {
completion(.Error(NSError(domain: "Networking", code: 500,
userInfo: nil)))
}
}.resume()
}
private func parseJSON(data: NSData)
->Result<[String: AnyObject]> {
var error: NSError?
if let json =
NSJSONSerialization.JSONObjectWithData(data, options:
nil, error: &error) as? [String: AnyObject] {
return .Success(Box(json))
} else {
return .Error(error!)
}
}
let imageSignal = gifSignal >>> getURL >>>
Thread.background >>> loadFromCache >>>
retryFromNetwork >>> Thread.main
class ViewController: UIViewController {
var signal: Signal<[Gif]>!
let searchBar = UISearchBar()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = searchBar
signal = searchBar.textSignal >>>
Network().search() >>> Thread.main
github.com/jensravens/reactivekitten
What’s next()?
Functors, Applicatives
and Monads in Pictures.
http://adit.io/posts/2013-04-17-
functors,_applicatives,_and_monads_in_pictures.html
The Introduction to RP
you’ve been missing.
https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
ReactiveCocoa 3
RxSwift
Interstellar
available on Carthage
jensravens/interstellar
Thank you.
@JensRavens
github.com/jensravens/interstellar

More Related Content

What's hot

ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
Allen Wirfs-Brock
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with Javassist
Anton Arhipov
 
Introduction to Elm
Introduction to ElmIntroduction to Elm
Introduction to Elm
Rogerio Chaves
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Mindfire Solutions
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
SmartLogic
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
Ian Robertson
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
José Paumard
 
50 new things we can do with Java 8
50 new things we can do with Java 850 new things we can do with Java 8
50 new things we can do with Java 8
José Paumard
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
William Farrell
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
Codemotion
 
Elm kyivfprog 2015
Elm kyivfprog 2015Elm kyivfprog 2015
Elm kyivfprog 2015
Alexander Mostovenko
 
How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...
Codemotion
 
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c HermioneJS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
JSFestUA
 
Migrations With Transmogrifier
Migrations With TransmogrifierMigrations With Transmogrifier
Migrations With TransmogrifierRok Garbas
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
José Paumard
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
Oswald Campesato
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
CodeOps Technologies LLP
 

What's hot (20)

ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with Javassist
 
Introduction to Elm
Introduction to ElmIntroduction to Elm
Introduction to Elm
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
50 new things we can do with Java 8
50 new things we can do with Java 850 new things we can do with Java 8
50 new things we can do with Java 8
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Elm kyivfprog 2015
Elm kyivfprog 2015Elm kyivfprog 2015
Elm kyivfprog 2015
 
How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...
 
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c HermioneJS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
 
Migrations With Transmogrifier
Migrations With TransmogrifierMigrations With Transmogrifier
Migrations With Transmogrifier
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 

Similar to Functional Reactive Programming without Black Magic (UIKonf 2015)

Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Codemotion
 
Taming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with InterstellarTaming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with Interstellar
Jens Ravens
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
Frank Müller
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
Vincent Pradeilles
 
[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8
Alonso Torres
 
F# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordF# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, Hereford
Kit Eason
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
Tor Ivry
 
Deep Learning, Scala, and Spark
Deep Learning, Scala, and SparkDeep Learning, Scala, and Spark
Deep Learning, Scala, and Spark
Oswald Campesato
 
Advanced #2 threading
Advanced #2   threadingAdvanced #2   threading
Advanced #2 threading
Vitali Pekelis
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already Know
Kevlin Henney
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей Родионов
Yandex
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
Spark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with SparkSpark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with Spark
samthemonad
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
intelliyole
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
pramode_ce
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
Jaanus Pöial
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
Fractal proj report 2
Fractal proj report 2Fractal proj report 2
Fractal proj report 2
rpiitcbme
 

Similar to Functional Reactive Programming without Black Magic (UIKonf 2015) (20)

Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
 
Taming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with InterstellarTaming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with Interstellar
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8
 
F# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordF# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, Hereford
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Deep Learning, Scala, and Spark
Deep Learning, Scala, and SparkDeep Learning, Scala, and Spark
Deep Learning, Scala, and Spark
 
Advanced #2 threading
Advanced #2   threadingAdvanced #2   threading
Advanced #2 threading
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already Know
 
functions
functionsfunctions
functions
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей Родионов
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Spark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with SparkSpark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with Spark
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Fractal proj report 2
Fractal proj report 2Fractal proj report 2
Fractal proj report 2
 

More from Jens Ravens

Turning it up to 11 - Scaling Ruby on Rails to 100k rps
Turning it up to 11 - Scaling Ruby on Rails to 100k rpsTurning it up to 11 - Scaling Ruby on Rails to 100k rps
Turning it up to 11 - Scaling Ruby on Rails to 100k rps
Jens Ravens
 
Server Side Swift - AppBuilders 2017
Server Side Swift - AppBuilders 2017Server Side Swift - AppBuilders 2017
Server Side Swift - AppBuilders 2017
Jens Ravens
 
Server Side Swift
Server Side SwiftServer Side Swift
Server Side Swift
Jens Ravens
 
Working with Xcode and Swift Package Manager
Working with Xcode and Swift Package ManagerWorking with Xcode and Swift Package Manager
Working with Xcode and Swift Package Manager
Jens Ravens
 
Server Side Swift with Swag
Server Side Swift with SwagServer Side Swift with Swag
Server Side Swift with Swag
Jens Ravens
 
Swift 2
Swift 2Swift 2
Swift 2
Jens Ravens
 
Swift: Immutability and You
Swift: Immutability and YouSwift: Immutability and You
Swift: Immutability and You
Jens Ravens
 

More from Jens Ravens (7)

Turning it up to 11 - Scaling Ruby on Rails to 100k rps
Turning it up to 11 - Scaling Ruby on Rails to 100k rpsTurning it up to 11 - Scaling Ruby on Rails to 100k rps
Turning it up to 11 - Scaling Ruby on Rails to 100k rps
 
Server Side Swift - AppBuilders 2017
Server Side Swift - AppBuilders 2017Server Side Swift - AppBuilders 2017
Server Side Swift - AppBuilders 2017
 
Server Side Swift
Server Side SwiftServer Side Swift
Server Side Swift
 
Working with Xcode and Swift Package Manager
Working with Xcode and Swift Package ManagerWorking with Xcode and Swift Package Manager
Working with Xcode and Swift Package Manager
 
Server Side Swift with Swag
Server Side Swift with SwagServer Side Swift with Swag
Server Side Swift with Swag
 
Swift 2
Swift 2Swift 2
Swift 2
 
Swift: Immutability and You
Swift: Immutability and YouSwift: Immutability and You
Swift: Immutability and You
 

Recently uploaded

May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 

Recently uploaded (20)

May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 

Functional Reactive Programming without Black Magic (UIKonf 2015)

  • 1. How to use Functional Reactive Programming without Black Magic
  • 2. let me = Person(name: "Jens Ravens") @JensRavens GitHub: JensRavens nerdgeschoss.de swift.berlin
  • 3. A short introduction to functional programming, the universe and everything.
  • 4. In the beginning McIlroy created the unix pipe. And he saw it was good. ls | grep *.jpg | sort
  • 6.
  • 7. starting from a blank slate
  • 9. And I promise not to use the scary M-word. me, 12 weeks ago.
  • 11. –Saunders Mac Lane All told, a monad is just a monoid in the category of endofunctors. “
  • 12. Monads are just Applicative Functors “
  • 13. ls | grep *.jpg | sort
  • 14. Buy it, use it, break it, fix it, Trash it, change it, mail - upgrade it. – Daft Punk, Technologic
  • 15. Buy it; if error { //TODO: Handle me! } else { use it; if error { //TODO: Handle me! } else { break it; if error { //TODO: Handle me!
  • 16. ls | grep *.jpg | sort
  • 18. The optional Monad let string: String? = "World" let greeting = string.map{"Hello ($0)”} //Hello World extension Optional { func bind<U> (f: T->U?) -> U? { if let result = self.map({f($0)}) { return result } else { return nil } } }
  • 19. The optional Monad let string: String? = "World" let greeting = string.map{"Hello ($0)”} //Hello World func greetOrNil(name: String)->String? { if name == "World" { return "Hello World" } else { return nil } } let greeting2 = string.bind(greetOrNil) //Hello World
  • 20. The optional Monad extension Optional { func bind<U> (f: T->U?) -> U? { if let result = self.map({f($0)}) { return result } else { return nil } } } extension Optional { func bind<U> (f: T->Optional<U>) -> Optional<U> { switch self { case let .Some(value): return f(value) case .None: return nil } } }
  • 21. The result Monad public enum Result<T> { case Success(Box<T>) case Error(NSError) }
  • 22. The result Monad public enum Result<T> { … public func map<U>(f: T -> U) -> Result<U> { switch self { case let .Success(v): return .Success(Box(f(v.value))) case let .Error(error): return .Error(error) } } … }
  • 23. The result Monad public enum Result<T> { … public func bind<U>(f: T -> Result<U>) -> Result<U> { switch self { case let .Success(v): return f(v.value) case let .Error(error): return .Error(error) } } … }
  • 24. ls | grep *.jpg | sort Monad Transform
  • 25. func parseString(data: NSData) -> Result<String> func parseJson(data: NSData) -> Result<[String: AnyObject]> func asyncGreeting(name: String, completion: Result<String>->Void)
  • 26. public func bind<U>(f:(T, (Result<U>->Void))->Void) -> (Result<U>->Void)->Void { return { g in switch self { case let .Success(v): f(v.value, g) case let .Error(error): g(.Error(error)) } } }
  • 28. ls | grep *.jpg | sort
  • 29. public final class Signal<T> { private var value: Result<T>? private var callbacks: [Result<T> -> Void] = [] public func subscribe(f: Result<T> -> Void) { if let value = value { f(value) } callbacks.append(f) } public func update(value: Result<T>) { self.value = value self.callbacks.map{$0(value)} } }
  • 30. public func map<U>(f: T -> U) -> Signal<U> { let signal = Signal<U>() subscribe { result in signal.update(result.map(f)) } return signal } public func bind<U>(f: T -> Result<U>) -> Signal<U> { let signal = Signal<U>() subscribe { result in signal.update(result.bind(f)) } return signal }
  • 31. public func bind<U>(f: (T, (Result<U>->Void))->Void) -> Signal<U> { let signal = Signal<U>() subscribe { value in value.bind(f)(signal.update) } return signal }
  • 33. the rise of custom operators
  • 34. infix operator >>> { associativity left precedence 160 } public func >>> <A,B> (left: Signal<A>, right: A->Result<B>) -> Signal<B> { return left.bind(right) } public func >>> <A,B>(left: Signal<A>, right: (A, (Result<B>->Void))->Void) -> Signal<B>{ return left.bind(right) } public func >>> <A,B> (left: Signal<A>, right: A->B) -> Signal<B> { return left.map(right) }
  • 35. ls | grep *.jpg | sort
  • 36. ls | grep *.jpg | sort ls >>> grep("*.jpg") >>> sort
  • 38. public final class Thread { public static func main<T>(a: T, completion: T->Void) { dispatch_async(dispatch_get_main_queue()) { completion(a) } } public static func background<T>(queue: dispatch_queue_t)(_ a: T, _ completion: T->Void) { dispatch_async(queue){ completion(a) } } } ls >>> Thread.background(queue) >>> grep("*.jpg") >>> sort >>> Thread.main
  • 40. var SignalHandle: UInt8 = 0 extension UITextField { public var textSignal: Signal<String> { let signal: Signal<String> if let handle = objc_getAssociatedObject(self, &SignalHandle) as? Signal<String> { signal = handle } else { signal = Signal("") NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("textChanged:"), name: UITextFieldTextDidChangeNotification, object: self) objc_setAssociatedObject(self, &SignalHandle, signal, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } return signal } public func textChanged(notification: NSNotification) { textSignal.update(.Success(Box(self.text))) } }
  • 41. If it’s variable, it qualifies as a Signal.
  • 42. ReactiveKitten It’s about gifs. And cats. And gifs of cats.
  • 43. userTyping >>> createURL >>> loadRequest >>> parseData >>> mainThread >>> displayCats The transform, the cat and you.
  • 44. import Interstellar private func request(path: String, completion: Result<NSData>->Void) { let url = NSURL(string: baseURL.stringByAppendingString(path))! let request = NSURLRequest(URL: url) session.dataTaskWithRequest(request){ data, response, error in if error != nil { completion(.Error(error)) } else if let response = response as? NSHTTPURLResponse { if response.statusCode >= 200 && response.statusCode<300 { completion(.Success(Box(data))) } else { completion(.Error(NSError(domain: "Networking", code: response.statusCode, userInfo: nil))) } } else { completion(.Error(NSError(domain: "Networking", code: 500, userInfo: nil))) } }.resume() }
  • 45. private func parseJSON(data: NSData) ->Result<[String: AnyObject]> { var error: NSError? if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? [String: AnyObject] { return .Success(Box(json)) } else { return .Error(error!) } }
  • 46. let imageSignal = gifSignal >>> getURL >>> Thread.background >>> loadFromCache >>> retryFromNetwork >>> Thread.main
  • 47. class ViewController: UIViewController { var signal: Signal<[Gif]>! let searchBar = UISearchBar() override func viewDidLoad() { super.viewDidLoad() navigationItem.titleView = searchBar signal = searchBar.textSignal >>> Network().search() >>> Thread.main
  • 50. Functors, Applicatives and Monads in Pictures. http://adit.io/posts/2013-04-17- functors,_applicatives,_and_monads_in_pictures.html
  • 51. The Introduction to RP you’ve been missing. https://gist.github.com/staltz/868e7e9bc2a7b8c1f754