2. Функционални Закачки
DESCRIPTION
Втора лекция от курса във ФМИ.TRANSCRIPT
2. Функционалнизакачки
speaker { [“Stefan”, “Kanev”].join(“ “) }speaker { “Nikolay” + “ “ + “Bachiyski” }on_date { @lecture_date || “13‐10‐2008” }
2. Функционалнизакачки
speaker { [“Stefan”, “Kanev”].join(“ “) }speaker { “Nikolay” + “ “ + “Bachiyski” }on_date { @lecture_date || “13‐10‐2008” }
Хиперкуб
1415926535 8979323846 2643383279 5028841971 69399375105820974944 5923078164 0628620899 8628034825 34211706798214808651 3282306647 0938446095 5058223172 53594081284811174502 8410270193 8521105559 6446229489 54930381964428810975 6659334461 2847564823 3786783165 27120190914564856692 3460348610 4543266482 1339360726 02491412737245870066 0631558817 4881520920 9628292540 91715364367892590360 0113305305 4882046652 1384146951 94151160943305727036 5759591953 0921861173 8193261179 31051185480744623799 6274956735 1885752724 8912279381 83011949129833673362 4406566430 8602139494 6395224737 19070217986094370277 0539217176 2931767523 8467481846 76694051320005681271 4526356082 7785771342 7577896091 73637178721468440901 2249534301 4654958537 1050792279 68925892354201995611 2129021960 8640344181 5981362977 47713099605187072113 4999999837 2978049951 0597317328 16096318595024459455 3469083026 4252230825 3344685035 2619311881
3.
DomainSpecificLanguage
mind.refresh
3.141_729
"Who is John Galt?"
[18, :f, "Sofia"]
{:jazz => ["Thelonious Monk", "Bill Evans"],:baroque => ["J.S. Bach", "Henry Purcell"],:classical => ["L.V. Beethoven", "W.A. Mozart"] }
if hungry?eat
elsesleep until hungry?
end
work until job.done?write_code(:ruby) while me.unhappy?eat(food) if hungry?write_code unless tired?
функции
функционалнопрограмиране
приема неща
връща неща
Обекти
приема неща
връща неща
order, change = use_machine(number, money)
order, change = use_machine(number, money)
Неща
coffee, change = use_machine(42, 1.50)
cup, cash = order("Cappuccino", 3) do |pref|pref.make_shortpref.add_sugar 2pref.add_extra :cream
end
приема неща
връща неща
приема нещаприема инструкциивръща неща
приема нещаприема инструкциивръща неща
Код
cup, cash = order("Cappuccino", 3) do |pref|pref.make_shortpref.add_sugar 2pref.add_extra :cream
end
>> numbers = [2, 3, 5, 7]
>> numbers.map { |x| x ** 2 }[4, 9, 25, 49]
>> numbers.select { |x| x > 4 }[5, 7]
извикване do |аргументи|код
end
извикване { |аргументи| код }
File.open("spendings").each_line do |line|next unless well_formed?(line)date, category, amount = line.splitcategory_sum[category] += amount.to_i
end
points.all? { |x,y| saved.include? [y,x] }
points.all? { |x,y| saved.include? [y,x] }
Блок / КорутинаИтератор
Улей
Щипки
Пич, извикайкорутината
def twiceyieldyield
end
twice { puts “Ruby rocks!” }
accumulate
def accum(start, items)result, items = start, items.dupyield(result, items.pop) until items.empty?result
end
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]puts accum(0, numbers) { |a, b| a + b }puts accum(1, numbers) { |a, b| a * b }
def with_primes(max)2.upto(max) do |n|
yield n unless (2...n).any? { |c| n % c == 0 }end
end
with_primes(10) { |x| puts x }
2.upto(10) do |n|
(2..10)(2…10)
any?all?
students.any? { |s| s.cheated? }numbers.all? { |x| x % 2 == 0 }
def with_primes(max)2.upto(max) do |n|
yield n unless (2...n).any? { |c| n % c == 0 }end
end
with_primes(10) { |x| puts x }
return
def magic_roots(numbers)numbers.map do |number|
return number ** 0.5 if number < 0(‐number) ** 0.5
endend
magic_roots([100, ‐25, ‐9, 16])
defreturn
end
nextbreak
n, found = 1, 0while true
n += 1next unless (2...n).any? { |a| n % a == 0 }found += 1puts "#{n} squared is #{n * n}"break if found >= 50
end
lucky = []users.each do |user|
next unless user.submitted_homework?lucky << userbreak if lucky.size >= 5
end
next(arg)break(arg)
item = items.first_itemfound = until item.nil?
break item if item.nice? and item.shiny?item = item.successor
end
def magic_roots(numbers)numbers.map do |number|
next number ** 0.5 if number < 0(‐number) ** 0.5
endend
magic_roots([100, ‐25, ‐9, 16])
points.all? { |x,y| saved.include? [y,x] }
Блок / КорутинаИтератор
Улей
Щипки
nextизлез от блока в итератора
breakизлез от итератора
lucky = []users.each do |user|next unless user.submitted_homework?lucky << userbreak if lucky.size >= 5
end
EnumerableArrayHash
collectselectinject
001:0> numbers = [1, 2, 3, 4, 5, 6, 7]=> [1, 2, 3, 4, 5, 6, 7]002:0> numbers.collect { |n| n ** 2 }=> [1, 4, 9, 16, 25, 36, 49]003:0> numbers.select { |n| n % 2 == 0 }=> [2, 4, 6]004:0> numbers.inject { |a, b| a + b }=> 28
emails = []users.each do |user|
emails << user.email if user.active?endreturn emails
users.select { |u| u.active? }.map { |u| u.email }
alias :collect, :mapalias :select, :find_all
001:0> people = ["Coltrane", "Monk", "Davis", "Evans"]002:0> people.all? { |x| x =~ /^[A‐Z][a‐z]+$/ }=> true003:0> people.any? { |name| name.include? 'trane' }=> true004:0> people.sort=> ["Coltrane", "Davis", "Evans", "Monk"]005:0> people.sort { |a, b| a.size <=> b.size }=> ["Monk", "Evans", "Davis", "Coltrane"]006:0> people.sort_by { |name| name.size }=> ["Monk", "Evans", "Davis", "Coltrane"]007:0> people.each_with_index { |n, i| puts "#{i}. #{n}" }0. Coltrane1. Monk2. Davis3. Evans008:0> people.detect { |name| name.include? "s" }=> "Davis“009:0> people.zip(["John", "Thelonious", "Miles", "Bill"])=> [["Coltrane", "John"], ["Monk", "Thelonious"], ["Davis", "Miles"], ["Evans", "Bill"]]
collect!select!
:symbol
symbol != char
Symbol.similar_to String
{:host => "fmi.rails‐bg.net",:port => 3306,:username => "website",:password => "gould",:database => "website",
}
wazup?!!!?!??1:!!??
def wazup?(a)puts "#{a} dat!"
end
def greet(name = "Unknown")puts "Greetings, #{name}"
end
greetgreet "Ruby"
connect :db, :host => "172.0.0.1", :port => 3306
connect(:db, {:host => "172.0.0.1", :port => 3306})
def connect(what, options = {})
form_for(url, html_options)
form_for {:action => "show", :id => 1}, :class => "horizontal"
form_for do:action => "show", :id => 1
end, :class => "horizontal"
001:0> hash, string = {"John" => "Coltrane", "Eddie" => "Vedder"}, "lar\nodi"002:0> puts hash.to_sJohnColtraneEddieVedder003:0> puts hash.inspect{"John"=>"Coltrane", "Eddie"=>"Vedder"}004:0> puts string.to_slarodi005:0> puts string.inspect"larodi"
to_sinspect
p foo"It is: %p" % foo
lambda
square = lambda { |x| x ** 2 }
puts square(7) # Не работи
puts square.call(7)
puts square[7]
seek = lambda do |needle, haystack|haystack.each do |item|
return true if item.equal?(needle)endfalse
end
square = ‐> (x) { x ** 2 }
1.9
Proc.new
root = Proc.new { |x| x ** 0.5 }
positivep = Proc.new { |x| x > 0 }
puts root[x] if positivep[x]
def my_map(list, operation)result = []list.each do |item|
result << operation[item]endresult
end
p my_map([2, 3, 5, 7], Proc.new { |x| x ** 2})
def my_map(list, operation)result = []list.each do |item|
result << yield(item)endresult
end
p my_map([2, 3, 5, 7]) { |x| x ** 2}
def my_map(list, operation)result = []list.each do |item|
result << yield(item)endresult
end
operation = Proc.new { |x| x ** 2 }p my_map([2, 3, 5, 7]) ... ???
proc→ block
def my_map(list, operation)result = []list.each do |item|
result << yield(item)endresult
end
operation = Proc.new { |x| x ** 2 }p my_map([2, 3, 5, 7], &operation)
block → proc
def my_map(list, &operation)result = []list.each do |item|
result << operation[item]endresult
end
p my_map([2, 3, 5, 7]) { |x| x ** 2 }
block_given?
def can_has_block?return block_given?
end
puts can_has_block? # falseputs can_has_block? { “plz } # true
def my_proc(&block)block
end
square = my_proc { |x| x ** 2 }puts square.call(7)puts square[42]
(‐>_{_%_})["(‐>_{_%%_})[%p]"]
def raise_to_power(numbers, power)numbers.map { |x| x ** power }
end
p raise_to_power([2, 3, 5, 7], 3)
def raise_to_power(numbers, power)numbers.map { |x| x ** power }
end
p raise_to_power([2, 3, 5, 7], 3)
def make_stamp(owner)time = Time.now
lambda do |thing|"#{time}: #{thing} is owned by #{owner}"
endend
sony = make_stamp("Sony")puts sony["Playstation"]sleep 1microsoft = make_stamp("Microsoft")puts microsoft["X‐box"]puts sony["Playstation"]
Mon Oct 13 16:37:22 +0300 2008: Playstationis owned by SonyMon Oct 13 16:37:23 +0300 2008: X‐box is owned by MicrosoftMon Oct 13 16:37:22 +0300 2008: Playstationis owned by Sony
def cuckoon = 0tick = lambda { n += 1 }tack = lambda { puts n }return tick, tack
end
one, two = cuckootwo[] # 0one[]two[] # 1one[]
three, four = cuckoofour[] # 0two[] # 2
can_haz_keushunz?