Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Munich Clojure Workshop - 07 - Let Over Lambda

Munich Clojure Workshop - 07 - Let Over Lambda

Copyright © 2012-2014 Clojure Workshop Team: Maximilian Karasz, Jan Stępień, Marek Kubica, Oleksandr Petrov

Commercial use of complete work or parts of work is not allowed to anyone except for Clojure Workshop Team at whole or in parts.

Licensed under Creative Commons Attribution-NonCommercial 3.0: http://creativecommons.org/licenses/by-nc/3.0/

When using complete work or parts of work, explicit attribution is required.

Clojure Workshops

October 11, 2013
Tweet

More Decks by Clojure Workshops

Other Decks in Technology

Transcript

  1. But why the hell"lambda"? Scheme calls it that. Also: lambda

    calculus (lambda (x) (* x 2)) Friday, October 11, 13
  2. What are scopes? a is “in scope”, b maybe. The

    bindings(assignments) a function can “see”: (fn [a] b) Friday, October 11, 13
  3. (fn [a] (fn [b] (+ a b))) Takes a and

    returns a function. A FunctionFactory if you please! The returned function takes b and returns a + b as result. Friday, October 11, 13
  4. This can be useful if you want to preconfigure a

    function: (defn addition [a] (fn [b] (+ a b))) (def increment (addition 1)) (map increment [1 2 3 4 5]) ;=> (2 3 4 5 6) Friday, October 11, 13
  5. Why should I want this? • Ever wrote a callback

    function? They often expect fixed arities. • Or just a higher order function like map? Friday, October 11, 13
  6. A hypothetical example GUI API (let [address (get-postal-address-of :santa)] (button

    :text "Send to santa" :onclick (fn [event widget] (send-mail-to address))])) 1 2 3 4 5 6 Function in line 5 has access to address, but only takes event and widget as arguments. Friday, October 11, 13
  7. What is this exactly? This returns a function, a so-called

    “closure”. It “closes over” a scope, so it knows that a is 1. (addition 1) Friday, October 11, 13
  8. ; old and busted ;-) (def increment #(+ 1 %))

    ; new hotness (def increment (partial + 1)) (map increment [1 2 3 4 5]) ;=> (2 3 4 5 6) It takes a function(+) and some arguments(1) and returns a closure with the arguments pre-set. Preconfigure a function which does not return a closure? partial to the rescue! Friday, October 11, 13