Domanda
Ho dei problemi con le chiusure e vorrei sapere cosa il codice equivalente per la procedura canonica di make-adder sarebbe in Ruby.
Nello schema sarebbe come:
(define (make-adder n)
(lambda (x) (+ x n))
Soluzione
In realtà è molto vicino ...
def make_addr n
lambda { |x| x + n }
end
t = make_addr 100
t.call 1
101
In 1.9 puoi usare ...
def make_addr n
->(x) { x + n }
end
Altri suggerimenti
Una differenza è che mentre Scheme ha solo un tipo di procedura, Ruby ne ha quattro. Il più delle volte, si comportano in modo abbastanza simile al tuo lambda standard, ma dovresti provare a comprendere tutti i dettagli in profondità .
Ecco un altro modo per farlo in 1.9:
make_adder = -> n, x { n + x }
hundred_adder = make_adder.curry[100]
hundred_adder[4] # => 104
Ecco un bel cast dello schermo che spiega i blocchi e le chiusure in Ruby: http://www.teachmetocode.com/screencasts/8
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow