3. Lambda calculus
Lambda expressions are composed of
variables v1, v2, ..., vn, ...
the abstraction symbols λ and .
parentheses ( )
The set of lambda expressions, Λ, can be defined recursively:
1. If x is a variable, then x ∈ Λ
2. If x is a variable and M ∈ Λ, then (λx.M) ∈ Λ
3. If M, N ∈ Λ, then (M N) ∈ Λ
Instances of rule 2 are known as abstractions and instances of rule 3 are
known as applications.
6. Enumerable
The Enumerable mixin provides collection
classes with several traversal and searching
methods, and with the ability to sort. The
class must provide a method each, which
yields successive members of the collection.
7. Enumerable
all? find minmax_by
any? find_all none?
chunk find_index one?
collect first partition
collect_concat flat_map reduce
count grep reject
cycle group_by reverse_each
detect include? select
drop inject slice_before
drop_while map sort
each_cons max sort_by
each_entry max_by take
each_slice member? take_while
each_with_index min to_a
each_with_object min_by zip
entries minmax
8. Enumerable
If Enumerable#max, min, or sort is used,
the objects in the collection must also
implement a meaningful <=> operator, as
these methods rely on an ordering between
members of the collection.
9. Better iteration
def crappy_method
results = []
@collection.each do |thing|
results << thing.property
end
results
end
def nicer_method
@collection.map {|a| a.property }
end
def more_concise_method
@collection.map &:property
end
10. each or map?
collection.each do |a|
do_something_with_side_effects(a)
end
another_collection = collection.map {|a| transform(a) }
11. do…end or {…}?
• do…end for multiple lines
• {…} when chaining
• do…end when there are side-effects
• do…end for control flow
12. Filtering
def crappy_filter
matches = []
@collection.each do |item|
matches << item if item.something?
end
matches
end
def nicer_sum
@collection.select {|a| a.something? }
end
def more_concise_sum
@collection.select &:something?
end
14. inject
def crappy_sum
sum = 0
@collection.each do |number|
sum += number
end
sum
end
def nicer_sum
@collection.inject(0) {|a, n| a + n }
end
def more_concise_sum
@collection.inject &:+
end
15. Chaining functions
def crappy_sum_of_odd_numbers
sum = 0
@collection.each do |number|
sum += number if number.odd?
end
sum
end
def sum_of_odd_numbers_using_inject
@collection.inject(0) {|a, n| n.odd? ? a + n : a }
end
def sum_of_odd_numbers_using_select_and_inject
@collection.select(&:odd?).inject(&:+)
end