Skip to content

Latest commit

 

History

History
79 lines (57 loc) · 2.69 KB

File metadata and controls

79 lines (57 loc) · 2.69 KB

08

Currying - if there’s a function returning another function we’re dealing with currying.

To make it more tangible let’s look at the example from the book:

(lambda (a)
  (lambda (x)
    (eq? x a))))

There’s an anonymous function that takes an argument a and returns an anonymous function that takes an argument x. Once the two arguments are passed the eq function is applied and we get a Boolean result.

If we want to pass the arguments to the anonymous function we need to wrap them in additional set of brackets.

(((lambda (a)
    (lambda (x)
      (> x a))) 4) 5)

The scope of the application of lambda (a) is 4. (lambda (a) …) 4) returns a function that takes x, 5 is applied. That in turn returns (> 5 4).

Describe in your own words the result of (rember-f test?) where test? is eq?.

(rember-f eq?) returns a function that takes two arguments atom and a list. It processes the list using the test? function and a given atom.

What role does #f play in yyy?

(define yyy
  (lambda (a l)
    ((insert-g seqrem) #f a l)))

(define seqrem
  (lambda (new old l)
    l))

#f is skipped, we can see that in the seared function which takes: #f an atom and a list, but returns just a list. #f is not used anywhere. atom is used for the comparison in the insert-g function.

Continuations

It took me a long while and multiple attempts to understand the concept of continuation / collector function. The basic idea is that regular recursive function is consing things inside of its body. While a collector is a type of an accumulator. The difference is that it is a function (not a variable) and the accumulation occurs when we keep stacking multiple collectors on top of each other.

Here’s and example of function add1. It adds 1 to each number in the list we give it. I’ll implement it in two styles, in first we gather the results of each pass in the function itself and we wrap it in recursion, in second we wrap the results in the collector function.

#lang racket

(require rackunit)

(define plus1-nat-recursion
  (lambda (lon)
    (cond
      ((null? lon) '())
      (else
       (cons (add1 (car lon))
             (plus1-nat-recursion (cdr lon)))))))

(check-equal? (plus1-nat-recursion '(1 2 3 4))
              '(2 3 4 5))

(define plus1-continuation
  (lambda (lon col)
    (cond
      ((null? lon) (col '()))
      (else
       (plus1-continuation (cdr lon)
              (lambda (result)
                (col
                   (cons (add1 (car lon)) result))))))))

(check-equal? (plus1-continuation '(1 2 3 4)
                                   (lambda (result) result))
              '(2 3 4 5))