Slide 1

Slide 1 text

REFACTORING RUBY WITH MONADS @tomstuart • GoGaRuCo • 2014-09-19

Slide 2

Slide 2 text

WARM UP

Slide 3

Slide 3 text

ANALOGIES

Slide 4

Slide 4 text

WHAT’S A STACK?

Slide 5

Slide 5 text

A KIND OF VALUE…

Slide 6

Slide 6 text

WITH CERTAIN OPERATIONS … …

Slide 7

Slide 7 text

#push(value) #pop #top #empty? .empty

Slide 8

Slide 8 text

THAT FOLLOW CERTAIN RULES …

Slide 9

Slide 9 text

stack.push(value).top == value stack.push(value).pop == stack empty.empty? == truee stack.push(value).empty? == false

Slide 10

Slide 10 text

WE CAN IMPLEMENT THEM HOWEVER WE LIKE

Slide 11

Slide 11 text

ArrayStack = Struct.new(:values) do def push(value) ArrayStack.new([value] + values) end ! def top values.first end ! def pop ArrayStack.new(values.drop(1)) end ! def empty? values.empty? end ! def self.empty new([]) end end

Slide 12

Slide 12 text

LinkedListStack = Struct.new(:top, :pop) do def push(value) LinkedListStack.new(value, self) end ! # def top # # we get this for free! # end ! # def pop # # and this! # end ! def empty? pop.nil? end ! def self.empty new(nil, nil) end end

Slide 13

Slide 13 text

WE CAN USE THEM WITHOUT KNOWING THEIR IMPLEMENTATION

Slide 14

Slide 14 text

>> stack = ArrayStack.empty => # >> stack.push('hello').push('world').pop.top => "hello" >> stack = LinkedListStack.empty => # >> stack.push('hello').push('world').pop.top => "hello"

Slide 15

Slide 15 text

WE CAN DEFINE MORE OPERATIONS

Slide 16

Slide 16 text

module Stack def size if empty? 0 else pop.size + 1 end end end ! ArrayStack.include(Stack) LinkedListStack.include(Stack)

Slide 17

Slide 17 text

>> ArrayStack.empty.size => 0 >> ArrayStack.empty.push('hello').push('world').size => 2 >> LinkedListStack.empty.size => 0 >> LinkedListStack.empty.push('hello').push('world').size => 2

Slide 18

Slide 18 text

OPERATIONS & RULES

Slide 19

Slide 19 text

COMMON INTERFACE & SHARED FUNCTIONALITY

Slide 20

Slide 20 text

WHAT’S A COLLECTION?

Slide 21

Slide 21 text

A KIND OF VALUE…

Slide 22

Slide 22 text

WITH CERTAIN OPERATIONS … …

Slide 23

Slide 23 text

#each

Slide 24

Slide 24 text

THAT FOLLOW CERTAIN RULES …

Slide 25

Slide 25 text

#each calls a block with a value zero or more times in immediate sequence

Slide 26

Slide 26 text

WE CAN IMPLEMENT IT HOWEVER WE LIKE

Slide 27

Slide 27 text

class HardcodedCollection def each(&block) block.call(1) block.call(2) block.call(3) block.call(4) block.call(5) end end

Slide 28

Slide 28 text

class GeneratedCollection def each(&block) number = 1 while number <= 5 block.call(number) number = number + 1 end end end

Slide 29

Slide 29 text

WE CAN USE IT WITHOUT KNOWING ITS IMPLEMENTATION

Slide 30

Slide 30 text

>> collection = HardcodedCollection.new => # >> collection.each { |n| puts n } 1 2 3 4 5 => nil >> collection = GeneratedCollection.new => # >> collection.each { |n| puts n } 1 2 3 4 5 => nil

Slide 31

Slide 31 text

WE CAN DEFINE MORE OPERATIONS

Slide 32

Slide 32 text

module Collection def select(&block) results = [] each do |value| results << value if block.call(value) end results end end ! HardcodedCollection.include(Collection) GeneratedCollection.include(Collection)

Slide 33

Slide 33 text

>> HardcodedCollection.new.select { |n| n.odd? } => [1, 3, 5] ! >> GeneratedCollection.new.select { |n| n.odd? } => [1, 3, 5]

Slide 34

Slide 34 text

OPERATIONS & RULES

Slide 35

Slide 35 text

COMMON INTERFACE & SHARED FUNCTIONALITY

Slide 36

Slide 36 text

WHAT ARE STACKS & COLLECTIONS?

Slide 37

Slide 37 text

ABSTRACT DATA TYPE

Slide 38

Slide 38 text

(ABSTRACT, BUT GOOD!)

Slide 39

Slide 39 text

LET’S DO SOME REFACTORING!

Slide 40

Slide 40 text

HANDLING NIL

Slide 41

Slide 41 text

Project = Struct.new(:creator) Person = Struct.new(:address) Address = Struct.new(:country) Country = Struct.new(:capital) City = Struct.new(:weather)

Slide 42

Slide 42 text

def weather_for(project) project.creator.address. country.capital.weather end

Slide 43

Slide 43 text

>> city = City.new('sunny') => # ! >> country = Country.new(city) => # ! >> address = Address.new(country) => # ! >> person = Person.new(address) => # ! >> project = Project.new(person) => #

Slide 44

Slide 44 text

>> weather_for(project) => "sunny"

Slide 45

Slide 45 text

>> bad_project = Project.new(Person.new(Address.new(nil))) => # ! >> weather_for(bad_project) NoMethodError: undefined method `capital' for nil:NilClass

Slide 46

Slide 46 text

def weather_for(project) project.creator.address. country.capital.weather end

Slide 47

Slide 47 text

def weather_for(project) creator = project.creator address = creator.address country = address.country capital = country.capital weather = capital.weather end

Slide 48

Slide 48 text

def weather_for(project) unless project.nil? creator = project.creator unless creator.nil? address = creator.address unless address.nil? country = address.country unless country.nil? capital = country.capital unless capital.nil? weather = capital.weather end end end end end end

Slide 49

Slide 49 text

def weather_for(project) unless project.nil? creator = project.creator end ! unless creator.nil? address = creator.address end ! unless address.nil? country = address.country end ! unless country.nil? capital = country.capital end ! unless capital.nil? weather = capital.weather end end

Slide 50

Slide 50 text

# activesupport/lib/active_support/core_ext/object/try.rb ! class Object def try(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) if respond_to?(a.first) end end end ! class NilClass def try(*args) nil end end

Slide 51

Slide 51 text

def weather_for(project) unless project.nil? creator = project.creator end ! unless creator.nil? address = creator.address end ! unless address.nil? country = address.country end ! unless country.nil? capital = country.capital end ! unless capital.nil? weather = capital.weather end end

Slide 52

Slide 52 text

def weather_for(project) creator = project.try(:creator) address = creator.try(:address) country = address.try(:country) capital = country.try(:capital) weather = capital.try(:weather) end

Slide 53

Slide 53 text

def weather_for(project) project. try(:creator). try(:address). try(:country). try(:capital). try(:weather) end

Slide 54

Slide 54 text

# activesupport/lib/active_support/core_ext/object/try.rb ! class Object def try(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) if respond_to?(a.first) end end end ! class NilClass def try(*args) nil end end

Slide 55

Slide 55 text

class Object remove_method :try end ! class NilClass remove_method :try end

Slide 56

Slide 56 text

Optional = Struct.new(:value)

Slide 57

Slide 57 text

>> optional_string = Optional.new('hello') => # >> optional_string.value => "hello" >> optional_string = Optional.new(nil) => # >> optional_string.value => nil

Slide 58

Slide 58 text

class Optional def try(*args, &block) if value.nil? nil else value.public_send(*args, &block) end end end

Slide 59

Slide 59 text

>> optional_string = Optional.new('hello') => # >> length = optional_string.try(:length) => 5 >> optional_string = Optional.new(nil) => # >> length = optional_string.try(:length) => nil

Slide 60

Slide 60 text

def weather_for(project) creator = project.try(:creator) address = creator.try(:address) country = address.try(:country) capital = country.try(:capital) weather = capital.try(:weather) end

Slide 61

Slide 61 text

def weather_for(project) optional_project = Optional.new(project) optional_creator = Optional.new(optional_project.try(:creator)) optional_address = Optional.new(optional_creator.try(:address)) optional_country = Optional.new(optional_address.try(:country)) optional_capital = Optional.new(optional_country.try(:capital)) optional_weather = Optional.new(optional_capital.try(:weather)) weather = optional_weather.value end

Slide 62

Slide 62 text

class Optional def try(*args, &block) if value.nil? nil else value.public_send(*args, &block) end end end

Slide 63

Slide 63 text

class Optional def try(&block) if value.nil? nil else block.call(value) end end end

Slide 64

Slide 64 text

def weather_for(project) optional_project = Optional.new(project) optional_creator = Optional.new(optional_project.try(:creator)) optional_address = Optional.new(optional_creator.try(:address)) optional_country = Optional.new(optional_address.try(:country)) optional_capital = Optional.new(optional_country.try(:capital)) optional_weather = Optional.new(optional_capital.try(:weather)) weather = optional_weather.value end

Slide 65

Slide 65 text

def weather_for(project) optional_project = Optional.new(project) optional_creator = optional_project.try { |project| Optional.new(project.creator) } optional_address = optional_creator.try { |creator| Optional.new(creator.address) } optional_country = optional_address.try { |address| Optional.new(address.country) } optional_capital = optional_country.try { |country| Optional.new(country.capital) } optional_weather = optional_capital.try { |capital| Optional.new(capital.weather) } weather = optional_weather.value end

Slide 66

Slide 66 text

>> weather_for(project) => "sunny" ! >> weather_for(bad_project) NoMethodError: undefined method `capital' for nil:NilClass

Slide 67

Slide 67 text

class Optional def try(&block) if value.nil? nil else block.call(value) end end end

Slide 68

Slide 68 text

class Optional def try(&block) if value.nil? Optional.new(nil) else block.call(value) end end end

Slide 69

Slide 69 text

>> weather_for(project) => "sunny" ! >> weather_for(bad_project) => nil

Slide 70

Slide 70 text

def weather_for(project) optional_project = Optional.new(project) optional_creator = optional_project.try { |project| Optional.new(project.creator) } optional_address = optional_creator.try { |creator| Optional.new(creator.address) } optional_country = optional_address.try { |address| Optional.new(address.country) } optional_capital = optional_country.try { |country| Optional.new(country.capital) } optional_weather = optional_capital.try { |capital| Optional.new(capital.weather) } weather = optional_weather.value end

Slide 71

Slide 71 text

class Optional def try(&block) if value.nil? Optional.new(nil) else block.call(value) end end end

Slide 72

Slide 72 text

class Optional def and_then(&block) if value.nil? Optional.new(nil) else block.call(value) end end end

Slide 73

Slide 73 text

def weather_for(project) optional_project = Optional.new(project) optional_creator = optional_project.and_then { |project| Optional.new(project.creator) } optional_address = optional_creator.and_then { |creator| Optional.new(creator.address) } optional_country = optional_address.and_then { |address| Optional.new(address.country) } optional_capital = optional_country.and_then { |country| Optional.new(country.capital) } optional_weather = optional_capital.and_then { |capital| Optional.new(capital.weather) } weather = optional_weather.value end

Slide 74

Slide 74 text

def weather_for(project) Optional.new(project). and_then { |project| Optional.new(project.creator) }. and_then { |creator| Optional.new(creator.address) }. and_then { |address| Optional.new(address.country) }. and_then { |country| Optional.new(country.capital) }. and_then { |capital| Optional.new(capital.weather) }. value end

Slide 75

Slide 75 text

class Optional def method_missing(*args, &block) and_then do |value| Optional.new(value.public_send(*args, &block)) end end end

Slide 76

Slide 76 text

def weather_for(project) Optional.new(project). and_then { |project| Optional.new(project.creator) }. and_then { |creator| Optional.new(creator.address) }. and_then { |address| Optional.new(address.country) }. and_then { |country| Optional.new(country.capital) }. and_then { |capital| Optional.new(capital.weather) }. value end

Slide 77

Slide 77 text

def weather_for(project) Optional.new(project). creator. address. country. capital. weather. value end

Slide 78

Slide 78 text

def weather_for(project) Optional.new(project). creator.address.country.capital.weather. value end

Slide 79

Slide 79 text

Optional = Struct.new(:value) do def and_then(&block) if value.nil? Optional.new(nil) else block.call(value) end end ! def method_missing(*args, &block) and_then do |value| Optional.new(value.public_send(*args, &block)) end end end

Slide 80

Slide 80 text

def weather_for(project) Optional.new(project). creator.address.country.capital.weather. value end

Slide 81

Slide 81 text

def weather_for(project) project.creator.address. country.capital.weather end

Slide 82

Slide 82 text

MULTIPLE RESULTS

Slide 83

Slide 83 text

Blog = Struct.new(:categories) Category = Struct.new(:posts) Post = Struct.new(:comments)

Slide 84

Slide 84 text

def words_in(blogs) blogs.flat_map { |blog| blog.categories.flat_map { |category| category.posts.flat_map { |post| post.comments.flat_map { |comment| comment.split(/\s+/) } } } } end

Slide 85

Slide 85 text

blogs = [ Blog.new([ Category.new([ Post.new(['I love cats', 'I love dogs']), Post.new(['I love mice', 'I love pigs']) ]), Category.new([ Post.new(['I hate cats', 'I hate dogs']), Post.new(['I hate mice', 'I hate pigs']) ]) ]), Blog.new([ Category.new([ Post.new(['Red is better than blue']) ]), Category.new([ Post.new(['Blue is better than red']) ]) ]) ]

Slide 86

Slide 86 text

>> words_in(blogs) => ["I", "love", "cats", "I", "love", "dogs", "I", "love", "mice", "I", "love", "pigs", "I", "hate", "cats", "I", "hate", "dogs", "I", "hate", "mice", "I", "hate", "pigs", "Red", "is", "better", "than", "blue", "Blue", "is", "better", "than", "red"]

Slide 87

Slide 87 text

def words_in(blogs) blogs.flat_map { |blog| blog.categories.flat_map { |category| category.posts.flat_map { |post| post.comments.flat_map { |comment| comment.split(/\s+/) } } } } end

Slide 88

Slide 88 text

Many = Struct.new(:values) do def and_then(&block) Many.new(values.map(&block).flat_map(&:values)) end end

Slide 89

Slide 89 text

def words_in(blogs) blogs.flat_map { |blog| blog.categories.flat_map { |category| category.posts.flat_map { |post| post.comments.flat_map { |comment| comment.split(/\s+/) } } } } end

Slide 90

Slide 90 text

def words_in(blogs) Many.new(blogs).and_then do |blog| Many.new(blog.categories).and_then do |category| Many.new(category.posts).and_then do |post| Many.new(post.comments).and_then do |comment| Many.new(comment.split(/\s+/)) end end end end.values end

Slide 91

Slide 91 text

def words_in(blogs) Many.new(blogs).and_then do |blog| Many.new(blog.categories) end.and_then do |category| Many.new(category.posts) end.and_then do |post| Many.new(post.comments) end.and_then do |comment| Many.new(comment.split(/\s+/)) end.values end

Slide 92

Slide 92 text

def words_in(blogs) Many.new(blogs). and_then { |blog | Many.new(blog.categories) }. and_then { |category| Many.new(category.posts) }. and_then { |post | Many.new(post.comments) }. and_then { |comment | Many.new(comment.split(/\s+/)) }. values end

Slide 93

Slide 93 text

class Many def method_missing(*args, &block) and_then do |value| Many.new(value.public_send(*args, &block)) end end end

Slide 94

Slide 94 text

def words_in(blogs) Many.new(blogs). and_then { |blog | Many.new(blog.categories) }. and_then { |category| Many.new(category.posts) }. and_then { |post | Many.new(post.comments) }. and_then { |comment | Many.new(comment.split(/\s+/)) }. values end

Slide 95

Slide 95 text

def words_in(blogs) Many.new(blogs). categories. posts. comments. split(/\s+/). values end

Slide 96

Slide 96 text

def words_in(blogs) Many.new(blogs). categories.posts.comments.split(/\s+/). values end

Slide 97

Slide 97 text

def words_in(blogs) blogs.categories.posts.comments.split(/\s+/) end

Slide 98

Slide 98 text

Many = Struct.new(:values) do def and_then(&block) Many.new(values.map(&block).flat_map(&:values)) end ! def method_missing(*args, &block) and_then do |value| Many.new(value.public_send(*args, &block)) end end end

Slide 99

Slide 99 text

ASYNCHRONOUS CODE

Slide 100

Slide 100 text

GET https://api.github.com/

Slide 101

Slide 101 text

{ "current_user_url": "https://api.github.com/user", "authorizations_url": "https://api.github.com/authorizations", "emails_url": "https://api.github.com/user/emails", "emojis_url": "https://api.github.com/emojis", "events_url": "https://api.github.com/events", "feeds_url": "https://api.github.com/feeds", "following_url": "https://api.github.com/user/following{/target}", "gists_url": "https://api.github.com/gists{/gist_id}", "hub_url": "https://api.github.com/hub", "issues_url": "https://api.github.com/issues", "keys_url": "https://api.github.com/user/keys", "notifications_url": "https://api.github.com/notifications", "organization_url": "https://api.github.com/orgs/{org}", "public_gists_url": "https://api.github.com/gists/public", "rate_limit_url": "https://api.github.com/rate_limit", "repository_url": "https://api.github.com/repos/{owner}/{repo}", "starred_url": "https://api.github.com/user/starred{/owner}{/repo}", "starred_gists_url": "https://api.github.com/gists/starred", "team_url": "https://api.github.com/teams", "user_url": "https://api.github.com/users/{user}" }

Slide 102

Slide 102 text

GET https://api.github.com/ GET https://api.github.com/orgs/ruby GET https://api.github.com/orgs/ruby/repos GET https://api.github.com/repos/ruby/ruby GET https://api.github.com/repos/ruby/ruby/contributors GET https://api.github.com/users/nobu

Slide 103

Slide 103 text

{ "login": "nobu", … "name": "Nobuyoshi Nakada", … }

Slide 104

Slide 104 text

def get_json(url, &success) Thread.new do uri = URI.parse(url) json = Net::HTTP.get(uri) value = JSON.parse(json) success.call(value) end end

Slide 105

Slide 105 text

get_json('https://api.github.com/') do |urls| org_url_template = URITemplate.new(urls['organization_url']) org_url = org_url_template.expand(org: 'ruby') ! get_json(org_url) do |org| repos_url = org['repos_url'] ! get_json(repos_url) do |repos| most_popular_repo = repos.max_by { |repo| repo['watchers_count'] } repo_url = most_popular_repo['url'] ! get_json(repo_url) do |repo| contributors_url = repo['contributors_url'] ! get_json(contributors_url) do |users| most_prolific_user = users.max_by { |user| user['contributions'] } user_url = most_prolific_user['url'] ! get_json(user_url) do |user| puts "The most influential Rubyist is #{user['name']} (#{user['login']})" end end end end end end

Slide 106

Slide 106 text

Eventually = Struct.new(:block) do def initialize(&block) super(block) end ! def run(&success) block.call(success) end end

Slide 107

Slide 107 text

class Eventually def and_then(&block) Eventually.new do |success| run do |value| block.call(value).run(&success) end end end end

Slide 108

Slide 108 text

get_json('https://api.github.com/') do |urls| org_url_template = URITemplate.new(urls['organization_url']) org_url = org_url_template.expand(org: 'ruby') ! get_json(org_url) do |org| repos_url = org['repos_url'] ! get_json(repos_url) do |repos| most_popular_repo = repos.max_by { |repo| repo['watchers_count'] } repo_url = most_popular_repo['url'] ! get_json(repo_url) do |repo| contributors_url = repo['contributors_url'] ! get_json(contributors_url) do |users| most_prolific_user = users.max_by { |user| user['contributions'] } user_url = most_prolific_user['url'] ! get_json(user_url) do |user| puts "The most influential Rubyist is #{user['name']} (#{user['login']})" end end end end end end

Slide 109

Slide 109 text

Eventually.new { |s| get_json('https://api.github.com/', &s) }.and_then do |urls| org_url_template = URITemplate.new(urls['organization_url']) org_url = org_url_template.expand(org: 'ruby') ! Eventually.new { |s| get_json(org_url, &s) }.and_then do |org| repos_url = org['repos_url'] ! Eventually.new { |s| get_json(repos_url, &s) }.and_then do |repos| most_popular_repo = repos.max_by { |repo| repo['watchers_count'] } repo_url = most_popular_repo['url'] ! Eventually.new { |s| get_json(repo_url, &s) }.and_then do |repo| contributors_url = repo['contributors_url'] ! Eventually.new { |s| get_json(contributors_url, &s) }.and_then do |users| most_prolific_user = users.max_by { |user| user['contributions'] } user_url = most_prolific_user['url'] ! Eventually.new { |s| get_json(user_url, &s) } end end end end end.run do |user| puts "The most influential Rubyist is #{user['name']} (#{user['login']})" end

Slide 110

Slide 110 text

def get_github_api_urls github_root_url = 'https://api.github.com/' ! Eventually.new { |success| get_json(github_root_url, &success) } end

Slide 111

Slide 111 text

Eventually.new { |s| get_json('https://api.github.com/', &s) }.and_then do |urls| org_url_template = URITemplate.new(urls['organization_url']) org_url = org_url_template.expand(org: 'ruby') ! Eventually.new { |s| get_json(org_url, &s) }.and_then do |org| repos_url = org['repos_url'] ! Eventually.new { |s| get_json(repos_url, &s) }.and_then do |repos| most_popular_repo = repos.max_by { |repo| repo['watchers_count'] } repo_url = most_popular_repo['url'] ! Eventually.new { |s| get_json(repo_url, &s) }.and_then do |repo| contributors_url = repo['contributors_url'] ! Eventually.new { |s| get_json(contributors_url, &s) }.and_then do |users| most_prolific_user = users.max_by { |user| user['contributions'] } user_url = most_prolific_user['url'] ! Eventually.new { |s| get_json(user_url, &s) } end end end end end.run do |user| puts "The most influential Rubyist is #{user['name']} (#{user['login']})" end

Slide 112

Slide 112 text

get_github_api_urls.and_then do |urls| org_url_template = URITemplate.new(urls['organization_url']) org_url = org_url_template.expand(org: 'ruby') ! Eventually.new { |s| get_json(org_url, &s) }.and_then do |org| repos_url = org['repos_url'] ! Eventually.new { |s| get_json(repos_url, &s) }.and_then do |repos| most_popular_repo = repos.max_by { |repo| repo['watchers_count'] } repo_url = most_popular_repo['url'] ! Eventually.new { |s| get_json(repo_url, &s) }.and_then do |repo| contributors_url = repo['contributors_url'] ! Eventually.new { |s| get_json(contributors_url, &s) }.and_then do |users| most_prolific_user = users.max_by { |user| user['contributions'] } user_url = most_prolific_user['url'] ! Eventually.new { |s| get_json(user_url, &s) } end end end end end.run do |user| puts "The most influential Rubyist is #{user['name']} (#{user['login']})" end

Slide 113

Slide 113 text

def get_org(urls, name) org_url_template = URITemplate.new(urls['organization_url']) org_url = org_url_template.expand(org: name) ! Eventually.new { |success| get_json(org_url, &success) } end

Slide 114

Slide 114 text

get_github_api_urls.and_then do |urls| org_url_template = URITemplate.new(urls['organization_url']) org_url = org_url_template.expand(org: 'ruby') ! Eventually.new { |s| get_json(org_url, &s) }.and_then do |org| repos_url = org['repos_url'] ! Eventually.new { |s| get_json(repos_url, &s) }.and_then do |repos| most_popular_repo = repos.max_by { |repo| repo['watchers_count'] } repo_url = most_popular_repo['url'] ! Eventually.new { |s| get_json(repo_url, &s) }.and_then do |repo| contributors_url = repo['contributors_url'] ! Eventually.new { |s| get_json(contributors_url, &s) }.and_then do |users| most_prolific_user = users.max_by { |user| user['contributions'] } user_url = most_prolific_user['url'] ! Eventually.new { |s| get_json(user_url, &s) } end end end end end.run do |user| puts "The most influential Rubyist is #{user['name']} (#{user['login']})" end

Slide 115

Slide 115 text

get_github_api_urls.and_then do |urls| ! ! ! get_org(urls, 'ruby').and_then do |org| repos_url = org['repos_url'] ! Eventually.new { |s| get_json(repos_url, &s) }.and_then do |repos| most_popular_repo = repos.max_by { |repo| repo['watchers_count'] } repo_url = most_popular_repo['url'] ! Eventually.new { |s| get_json(repo_url, &s) }.and_then do |repo| contributors_url = repo['contributors_url'] ! Eventually.new { |s| get_json(contributors_url, &s) }.and_then do |users| most_prolific_user = users.max_by { |user| user['contributions'] } user_url = most_prolific_user['url'] ! Eventually.new { |s| get_json(user_url, &s) } end end end end end.run do |user| puts "The most influential Rubyist is #{user['name']} (#{user['login']})" end

Slide 116

Slide 116 text

def get_repos(org) repos_url = org['repos_url'] ! Eventually.new { |success| get_json(repos_url, &success) } end

Slide 117

Slide 117 text

get_github_api_urls.and_then do |urls| ! ! ! get_org(urls, 'ruby').and_then do |org| repos_url = org['repos_url'] ! Eventually.new { |s| get_json(repos_url, &s) }.and_then do |repos| most_popular_repo = repos.max_by { |repo| repo['watchers_count'] } repo_url = most_popular_repo['url'] ! Eventually.new { |s| get_json(repo_url, &s) }.and_then do |repo| contributors_url = repo['contributors_url'] ! Eventually.new { |s| get_json(contributors_url, &s) }.and_then do |users| most_prolific_user = users.max_by { |user| user['contributions'] } user_url = most_prolific_user['url'] ! Eventually.new { |s| get_json(user_url, &s) } end end end end end.run do |user| puts "The most influential Rubyist is #{user['name']} (#{user['login']})" end

Slide 118

Slide 118 text

get_github_api_urls.and_then do |urls| ! ! ! get_org(urls, 'ruby').and_then do |org| ! ! get_repos(org).and_then do |repos| most_popular_repo = repos.max_by { |repo| repo['watchers_count'] } repo_url = most_popular_repo['url'] ! Eventually.new { |s| get_json(repo_url, &s) }.and_then do |repo| contributors_url = repo['contributors_url'] ! Eventually.new { |s| get_json(contributors_url, &s) }.and_then do |users| most_prolific_user = users.max_by { |user| user['contributions'] } user_url = most_prolific_user['url'] ! Eventually.new { |s| get_json(user_url, &s) } end end end end end.run do |user| puts "The most influential Rubyist is #{user['name']} (#{user['login']})" end

Slide 119

Slide 119 text

get_github_api_urls.and_then do |urls| ! ! ! get_org(urls, 'ruby').and_then do |org| ! ! get_repos(org).and_then do |repos| ! ! ! get_most_popular_repo(repos).and_then do |repo| ! ! get_contributors(repo).and_then do |users| ! ! ! get_most_prolific_user(users) end end end end end.run do |user| puts "The most influential Rubyist is #{user['name']} (#{user['login']})" end

Slide 120

Slide 120 text

get_github_api_urls.and_then do |urls| get_org(urls, 'ruby').and_then do |org| get_repos(org).and_then do |repos| get_most_popular_repo(repos).and_then do |repo| get_contributors(repo).and_then do |users| get_most_prolific_user(users) end end end end end.run do |user| puts 'The most influential Rubyist is' + " #{user['name']} (#{user['login']})" end

Slide 121

Slide 121 text

get_github_api_urls.and_then do |urls| get_org(urls, 'ruby') end.and_then do |org| get_repos(org) end.and_then do |repos| get_most_popular_repo(repos) end.and_then do |repo| get_contributors(repo) end.and_then do |users| get_most_prolific_user(users) end.run do |user| puts 'The most influential Rubyist is' + " #{user['name']} (#{user['login']})" end

Slide 122

Slide 122 text

get_github_api_urls. and_then { |urls | get_org(urls, 'ruby') }. and_then { |org | get_repos(org) }. and_then { |repos| get_most_popular_repo(repos) }. and_then { |repo | get_contributors(repo) }. and_then { |users| get_most_prolific_user(users) }. run do |user| puts 'The most influential Rubyist is' + " #{user['name']} (#{user['login']})" end

Slide 123

Slide 123 text

Eventually = Struct.new(:block) do def initialize(&block) super(block) end ! def run(&success) block.call(success) end ! def and_then(&block) Eventually.new do |success| run do |value| block.call(value).run(&success) end end end end

Slide 124

Slide 124 text

SO… WHAT?

Slide 125

Slide 125 text

Optional = Struct.new(:value) do def and_then(&block) if value.nil? Optional.new(nil) else block.call(value) end end end Eventually = Struct.new(:block) do def and_then(&block) Eventually.new do |success| run do |value| block.call(value).run(&success) end end end end Many = Struct.new(:values) do def and_then(&block) Many.new( values.map(&block).flat_map(&:values) ) end end

Slide 126

Slide 126 text

Optional, Many & Eventually ARE MONADS

Slide 127

Slide 127 text

ABSTRACT DATA TYPE

Slide 128

Slide 128 text

SOME OPERATIONS

Slide 129

Slide 129 text

#and_then .from_value

Slide 130

Slide 130 text

def Optional.from_value(value) Optional.new(value) end ! def Many.from_value(value) Many.new([value]) end ! def Eventually.from_value(value) Eventually.new { |success| success.call(value) } end

Slide 131

Slide 131 text

SOME RULES

Slide 132

Slide 132 text

#and_then calls a block with a value zero or more times at some point

Slide 133

Slide 133 text

#and_then returns an instance of the same monad

Slide 134

Slide 134 text

Optional = Struct.new(:value) do def and_then(&block) if value.nil? Optional.new(nil) else block.call(value) end end end Eventually = Struct.new(:block) do def and_then(&block) Eventually.new do |success| run do |value| block.call(value).run(&success) end end end end Many = Struct.new(:values) do def and_then(&block) Many.new( values.map(&block).flat_map(&:values) ) end end

Slide 135

Slide 135 text

#and_then and .from_value don’t mess with the value

Slide 136

Slide 136 text

COMMON INTERFACE

Slide 137

Slide 137 text

#and_then lets us connect together a sequence of operations

Slide 138

Slide 138 text

Optional#and_then: do the next thing if the value isn’t nil

Slide 139

Slide 139 text

Many#and_then: do the next thing once for each value

Slide 140

Slide 140 text

Eventually#and_then: do the next thing whenever the value is ready

Slide 141

Slide 141 text

SHARED FUNCTIONALITY

Slide 142

Slide 142 text

#within

Slide 143

Slide 143 text

module Monad def within(&block) and_then do |value| self.class.from_value(block.call(value)) end end end ! Optional.include(Monad) Many.include(Monad) Eventually.include(Monad)

Slide 144

Slide 144 text

we can write code that uses #within without knowing which monad it is

Slide 145

Slide 145 text

def description_from(containing_json) containing_json.within do |json| JSON.parse(json) end.within do |hash| "#{hash['name']} (#{hash['login']})" end end

Slide 146

Slide 146 text

>> optional_json = Optional.new('{ "login": "nobu", "name": "Nobuyoshi Nakada" }') => # >> optional_description = description_from(optional_json) => # >> optional_description.value => "Nobuyoshi Nakada (nobu)"

Slide 147

Slide 147 text

>> optional_json = Optional.new(nil) => # >> optional_description = description_from(optional_json) => # >> optional_description.value => nil

Slide 148

Slide 148 text

>> many_jsons = Many.new([ '{ "login": "nobu", "name": "Nobuyoshi Nakada" }', '{ "login": "matz", "name": "Yukihiro Matsumoto" }' ]) => # >> many_descriptions = description_from(many_jsons) => # >> many_descriptions.values => ["Nobuyoshi Nakada (nobu)", "Yukihiro Matsumoto (matz)"]

Slide 149

Slide 149 text

>> eventually_json = Eventually.new do |success| Thread.new do uri = URI.parse('https://api.github.com/users/nobu') json = Net::HTTP.get(uri) success.call(json) end end => #> >> eventually_description = description_from(eventually_json) => #> >> eventually_description.run { |description| puts description } => # Nobuyoshi Nakada (nobu)

Slide 150

Slide 150 text

def description_from(containing_json) containing_json.within do |json| JSON.parse(json) end.within do |hash| "#{hash['name']} (#{hash['login']})" end end

Slide 151

Slide 151 text

(ABSTRACT, BUT GOOD!)

Slide 152

Slide 152 text

https://github.com/tomstuart/monads gem install monads

Slide 153

Slide 153 text

Stuart Understanding Computation From Simple Machines to Impossible Programs Tom Stuart Understanding Computation .com @oreillymedia k.com/oreilly uart, a computer t and programmer, ounder of Codon, a product consultancy don. He works as a ant, mentor, and helping companies ove the quality and of their approach to g software products. http://computationbook.com/

Slide 154

Slide 154 text

thanks! @tomstuart • [email protected] • computationbook.com https://github.com/tomstuart/monads gem install monads