Slide 1

Slide 1 text

Let over Lambda Friday, October 11, 13

Slide 2

Slide 2 text

What is a lambda? Friday, October 11, 13

Slide 3

Slide 3 text

A lambda is a function Friday, October 11, 13

Slide 4

Slide 4 text

A lambda is a function (fn [x] (* x 2)) Friday, October 11, 13

Slide 5

Slide 5 text

But why the hell"lambda"? Scheme calls it that. Also: lambda calculus (lambda (x) (* x 2)) Friday, October 11, 13

Slide 6

Slide 6 text

What are scopes? Friday, October 11, 13

Slide 7

Slide 7 text

What are scopes? a is “in scope”, b maybe. The bindings(assignments) a function can “see”: (fn [a] b) Friday, October 11, 13

Slide 8

Slide 8 text

(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

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

Closure Friday, October 11, 13

Slide 14

Slide 14 text

Clojure Friday, October 11, 13

Slide 15

Slide 15 text

I see what you did there, Rich Hickey. Friday, October 11, 13

Slide 16

Slide 16 text

; 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

Slide 17

Slide 17 text

Other fun things with lambdas and scopes Friday, October 11, 13

Slide 18

Slide 18 text

Dynamic scoping with binding Friday, October 11, 13

Slide 19

Slide 19 text

Data access control Friday, October 11, 13

Slide 20

Slide 20 text

Data access control As we'll implement in the exercises. Friday, October 11, 13