Created
January 26, 2015 05:26
-
-
Save samuelreh/4754845520181143ffd7 to your computer and use it in GitHub Desktop.
Mary Rose Cook's Practical Intro to FP ported to Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Squares | |
# | |
squares = lambda do |nums| | |
nums.map do |num| | |
num * num | |
end | |
end | |
p squares.call([1,2,3,4]) | |
# | |
# Hash | |
# | |
hash = lambda do |items| | |
items.map do |item| | |
item.hash | |
end | |
end | |
p hash.call ['Mary', 'Isla', 'Sam'] | |
# | |
# Sum | |
# | |
sum = lambda do |nums| | |
nums.reduce(0) do |result, num| | |
result + num | |
end | |
end | |
p sum.call [0, 1, 2, 3, 4] | |
# | |
# Count Occurances | |
# | |
count_occurances = lambda do |sentences| | |
sentences.reduce(0) do |result, sentence| | |
result + sentence.scan(/Sam/).count | |
end | |
end | |
p count_occurances.call( | |
['Mary read a story to Sam and Isla.', | |
'Isla Sam cuddled Sam.', | |
'Sam chortled.'] | |
) | |
# | |
# Assoc dupes a hash and changes an attribute | |
# | |
assoc = lambda do |key, value, item| | |
new_item = item.dup | |
new_item[key] = value | |
new_item | |
end | |
call = lambda do |fn, key| | |
lambda do |item| | |
assoc.call(key, fn.call(item[key]), item) | |
end | |
end | |
set_canada = assoc.curry.(:country, 'Canada') | |
strip_name = lambda do |item| | |
strip = lambda { |name| name.gsub('.', '') } | |
call.call(strip, :name).call(item) | |
end | |
capitalize_name = lambda do |item| | |
capitalize = lambda { |name| name.split(" ").map(&:capitalize).join(" ") } | |
call.call(capitalize, :name).call(item) | |
end | |
pipeline = lambda do |items, methods| | |
methods.reduce(items) do |result, method| | |
result.map do |item| | |
method.call(item) | |
end | |
end | |
end | |
bands = [{ name: 'sunset rubdown', country: 'UK', active: false }, | |
{ name: 'women', country: 'Germany', active: false }, | |
{ name: 'a silver mt. zion', country: 'Spain', active: true }] | |
p pipeline.call(bands, [set_canada, strip_name, capitalize_name]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment