Martin Chabot

Twitter: @martinosis

Functional Ruby

Ruby is OO language

With

Good functionnal support

Blocks

10.times { |a| puts "count #{a}" }

Lambdas

add = -> (a, b) { a + b } 
add.(2, 3) # => 7
display = -> a { puts "count #{a}" }
puts 10.times(&display)

Partial application

Partial application refers to the process of fixing a number of arguments to a function, producing another function of smaller arity.

add = -> a { -> b {a + b} }
add2 =  add.(2) # => #<Proc ...>
add2.(3)  # => 5
multi_add = -> a { -> b { -> c { a + b + c } } }
multi_add.(10).(1).(5) # => 16

Defining your lambda this way can be teadious

Proc#curry

add =  -> (a, b) { a + b }.curry
add2 =  add.(2)
add2.(3) # => 5

?????

OO Dependency injection

class LanguageCounter
  def initialize(logger, client)
    @logger = logger
    @client = client
  end

  def call(user_name)
    repos = @client.repos(user_name)
    @logger.info("REPOS = \n #{repos}")
    repos.group_by { |a| a["language"] }.map { |key, val| [key, val.count] }.to_h
  end
end
class GithubClient
  def repos(user_name)
    json = open("https://api.github.com/users/#{user_name}/repos?per_page=100").read
    JSON.parse(json)
  end
end

logger = Logger.new($stdout)
client = GithubClient.new
counter = LanguageCounter.new(logger, client)

puts counter.call("martinos")
language_count = -> printer, fetch_repo, user_name {
  repos = fetch_repo.(user_name)
  printer.("REPOS = \n  #{repos}")
  repos.group_by { |a| a["language"] }
       .map { |key, val| [key, val.count] }
       .to_h
}.curry
fetch_repo = -> user_name { 
  json = open("https://api.github.com/users/#{user_name}/repos?per_page=100").read 
  JSON.parse(json)
}

printer = $stdout.method(:puts)
get_names = language_count.(printer).(fetch_repo)
printer = -> a { a }
# or
printer = -> a { logger.info(a) }

Function Composition

require 'superators19'

class Proc
  superator ">>~" do |fn|
    -> a { fn.(self.(a)) } 
  end
end
mult = -> a, b { a * b }.curry

doing = add.(2) >>~ mult.(3)

doing.(2) # => 12

Conclusion

References

Learning

```

#### Talks