The following code is used to implement a built-in function called "build-list":
(define (my-build-list-book n f)
(define (builder k)
(cond [(= n k) empty]
[else (cons (f k) (builder (add1 k)))]))
(builder 0))
(my-build-list-book 10 add1)
>> '(1 2 3 4 5 6 7 8 9 10)
Is this a recursive definition of an iterative procedure or a recursive definition of a recursive procedure?
builder is recursive because it calls itself: (builder (add1 k))
It's not tail recursive because the call to itself is not done in the place where a value is returned from the original procedure. It uses the result of the recursive call as an argument to cons rather than as the return value.
A tail-recursive variant would end with something like:
[else (builder ...)]
Converting a function like this to tail-recursion generally requires adding an additional argument that contains the accumulated result, which is returned by the base case.
(define (my-build-list-book n f)
(define (builder k result)
(cond [(= n k) result]
[else (builder (add1 k) (cons (f k) result))]))
(builder 0 '()))
I'm not sure what you mean by "long tail recursion", I've never heard that phrase and I can't find it with Google.
Related
These two examples do the factorial of a number:
(define (factorial n)
(define (execute n result)
(cond
[(> 2 n) result]
[else (execute (- n 1) (* result n))]))
(execute n 1))
And
(define (factorial n)
(let loop ((curr n)
(result 1))
(cond
[(> 2 curr) result]
[else (loop (- curr 1) (* result curr))])))
The difference reside in using the named-let. Are they both pure and tail recursive functions?
Yes, they are tail-recursive, and they're essentially equivalent.
A named let is just a shorthand for a function definition along with a first call using the initial values as the arguments.
A function is tail-recursive if all its calls to itself are in tail positions, i.e. it simply returns the value of that call. In the first function, the recursive call to execute is in the tail position; in the second function the same is true of the call to loop.
I have been trying to implement a for loop inside a recursive function using a for loop. Using the already implemented "for" in racket is not permitted. Is there a way to implement such a case?
Note : I am using an Intermediate Student Language for the same.
First off for in #lang racket is purely for side effects. Usually you would want the other variants like for/map and for/fold that ends up producing a value.
Racket is a descendant of Scheme and all looping in it is just syntactic sugar for a recursive function being applied. As an example the do loop:
(do ((vec (make-vector 5))
(i 0 (+ i 1)))
((= i 5) vec)
(vector-set! vec i i))
; ==> #(0 1 2 3 4)
In reality the language doesn't have do as a primitive. Instead the implementation usually have a macro that makes it into this (or something similar):
(let loop ((vec (make-vector 5)) (i 0))
(if (= i 5)
vec
(begin
(vector-set! vec i i)
(loop vec (+ i 1)))))
This is of course just sugar for this:
((letrec ((loop (lambda (vec i)
(if (= i 5)
vec
(begin
(vector-set! vec i i)
(loop vec (+ i 1)))))))
loop)
(make-vector 5) (i 0))
And of course letrec is also sugar... It goes down to just using lambda at some level.
Here is an example. The function squares produces a list of the first n square numbers. To produce that list, it loops over the number 0, ..., n-1 using an index i.
(define (squares n)
(define (loop i)
(if (= i n)
'()
(cons (* i i) (loop (+ i 1)))))
(loop 0))
(squares 10)
I create a function which create list. I want to use that list in an another function so how can I do this?
(define (myfunc L n)
(if (= n 0)
empty
(cons (list-ref L (random 26))
(myfunc L (- n 1)))))
I want to assing this function as a list to make it useful for using in an another function.
Starting with your definition:
(define (myfunc L n)
(if (= n 0)
empty
(cons (list-ref L (random 26))
(myfunc L (- n 1)))))
Functions that take Functions
Because Schemes treat functions as first class values, myfunc can be passed as a function to another function. We can write a second function that accepts a function as an argument:
(define (another-function a-function L n)
(print "another-function: ")
(a-function L n)) ; call a-function just like a built in function
We can pass myfunc into another-function. Then my-func will be called within another-function:
racket> (another-function myfunc (range 40) 4)
"another-function: "'(0 9 13 2)
This shows how functions are passed as arguments. The important idea is Scheme passes functions as functions not as lists. Scheme passes functions as values not as source code that will be evaluated to a value.
Functions Returning Functions
To drive home the idea that functions are values, we look at functions that return functions. Here is a function that returns a function like myfunc except that we can use a different value instead of 26:
(define (make-myfunc r)
(define (inner-myfunc L n) ; define a new function like myfunc
(if (= n 0)
empty
(cons (list-ref L (random r)) ; use r instead of 26
(inner-myfunc L (- n 1)))))
inner-myfunc) ; return the new function
We can use it like this:
racket> (define myfunc4 (make-myfunc 4))
racket> (myfunc4 (range 40) 4)
'(2 0 3 0)
Functions that take functions and return functions
Here is a function that takes one function and returns a different function:
(define (make-another-function a-function)
;; because the function we are returning does not call
;; itself recursively, we can use lambda instead of define.
(lambda (L n)
(print "made by make-another-function: ")
(a-function L n)))
And here it is in use:
racket> (define yet-another-function (make-another-function myfunc))
racket> (yet-another-function (range 40) 3)
"made by make-another-function: "'(1 18 16)
Does scheme have a function to call a function n times. I don't want map/for-each as the function doesn't have any arguments. Something along the lines of this :-
(define (call-n-times proc n)
(if (= 0 n)
'()
(cons (proc) (call-n-times proc (- n 1)))))
(call-n-times read 10)
SRFI 1 has a list-tabulate function that can build a list from calling a given function, with arguments 0 through (- n 1). However, it does not guarantee the order of execution (in fact, many implementations start from (- n 1) and go down), so it's not ideal for calling read with.
In Racket, you can do this:
(for/list ((i 10))
(read))
to call read 10 times and collect the result of each; and it would be done left-to-right. But since you tagged your question for Guile, we need to do something different.
Luckily, Guile has SRFI 42, which enables you to do:
(list-ec (: i 10)
(read))
Implementing tail-recursion modulo cons optimization by hand, to build the resulting list with O(1) extra space:
(define (iterate0-n proc n) ; iterate a 0-arguments procedure n times
(let ((res (list 1))) ; return a list of results in order
(let loop ((i n) (p res))
(if (< i 1)
(cdr res)
(begin
(set-cdr! p (list (proc)))
(loop (- i 1) (cdr p)))))))
This technique first (?) described in Friedman and Wise's TR19.
The following example involves jumping into continuation and exiting out. Can somebody explain the flow of the function. I am moving in a circle around continuation, and do not know the entry and exit points of the function.
(define (prod-iterator lst)
(letrec ((return-result empty)
(resume-visit (lambda (dummy) (process-list lst 1)))
(process-list
(lambda (lst p)
(if (empty? lst)
(begin
(set! resume-visit (lambda (dummy) 0))
(return-result p))
(if (= 0 (first lst))
(begin
(call/cc ; Want to continue here after delivering result
(lambda (k)
(set! resume-visit k)
(return-result p)))
(process-list (rest lst) 1))
(process-list (rest lst) (* p (first lst))))))))
(lambda ()
(call/cc
(lambda (k)
(set! return-result k)
(resume-visit 'dummy))))))
(define iter (prod-iterator '(1 2 3 0 4 5 6 0 7 0 0 8 9)))
(iter) ; 6
(iter) ; 120
(iter) ; 7
(iter) ; 1
(iter) ; 72
(iter) ; 0
(iter) ; 0
Thanks.
The procedure iterates over a list, multiplying non-zero members and returning a result each time a zero is found. Resume-visit stores the continuation for processing the rest of the list, and return-result has the continuation of the call-site of the iterator. In the beginning, resume-visit is defined to process the entire list. Each time a zero is found, a continuation is captured, which when invoked executes (process-list (rest lst) 1) for whatever value lst had at the time. When the list is exhausted, resume-visit is set to a dummy procedure. Moreover, every time the program calls iter, it executes the following:
(call/cc
(lambda (k)
(set! return-result k)
(resume-visit 'dummy)))
That is, it captures the continuation of the caller, invoking it returns a value to the caller. The continuation is stored and the program jumps to process the rest of the list.
When the procedure calls resume-visit, the loop is entered, when return-result is called, the loop is exited.
If we want to examine process-list in more detail, let's assume the list is non-empty. Tho procedure employs basic recursion, accumulating a result until a zero is found. At that point, p is the accumulated value and lst is the list containing the zero. When we have a construction like (begin (call/cc (lambda (k) first)) rest), we first execute first expressions with k bound to a continuation. It is a procedure that when invoked, executes rest expressions. In this case, that continuation is stored and another continuation is invoked, which returns the accumulated result p to the caller of iter. That continuation will be invoked the next time iter is called, then the loop continues with the rest of the list. That is the point with the continuations, everything else is basic recursion.
What you need to keep in mind is that, a call to (call/cc f) will apply the function f passed as argument to call/cc to the current continuation. If that continuation is called with some argument a inside the function f, the execution will go to the corresponding call to call/cc, and the argument a will be returned as the return value of that call/cc.
Your program stores the continuation of "calling call/cc in iter" in the variable return-result, and begins processing the list. It multiplies the first 3 non-zero elements of the list before encountering the first 0. When it sees the 0, the continuation "processing the list element 0" is stored in resume-visit, and the value p is returned to the continuation return-result by calling (return-result p). This call will make the execution go back to the call/cc in iter, and that call/cc returns the passed value of p. So you see the first output 6.
The rest calls to iter are similar and will make the execution go back and forth between such two continuations. Manual analysis may be a little brain-twisting, you have to know what the execution context is when a continuation is restored.
You could achieve the same this way:
(define (prod-iter lst) (fold * 1 (remove zero? lst)))
... even though it could perform better by traversing only once.
For continuations, recall (pun intended) that all call/cc does is wait for "k" to be applied this way:
(call/cc (lambda (k) (k 'return-value)))
=> return-value
The trick here is that you can let call/cc return its own continuation so that it can be applied elsewhere after call/cc has returned like this:
;; returns twice; once to get bound to k, the other to return blah
(let ([k (call/cc (lambda (k) k))]) ;; k gets bound to a continuation
(k 'blah)) ;; k returns here
=> blah
This lets a continuation return more than once by saving it in a variable. Continuations simply return the value they are applied to.
Closures are functions that carry their environment variables along with them before arguments get bounded to them. They are ordinary lambdas.
Continuation-passing style is a way to pass closures as arguments to be applied later. We say that these closure arguments are continuations. Here's half of the current code from my sudoku generator/solver as an example demonstrating how continuation-passing style can simplify your algorithms:
#| the grid is internally represented as a vector of 81 numbers
example: (make-vector 81 0)
this builds a list of indexes |#
(define (cell n) (list (+ (* (car 9) (cadr n))))
(define (row n) (iota 9 (* n 9)))
(define (column n) (iota 9 n 9))
(define (region n)
(let* ([end (+ (* (floor-quotient n 3) 27)
(* (remainder n 3) 3))]
[i (+ end 21)])
(do ([i i
(- i (if (zero? (remainder i 3)) 7 1))]
[ls '() (cons (vector-ref *grid* i) ls)])
((= i end) ls))))
#| f is the continuation
usage examples:
(grid-ref *grid* row 0)
(grid-set! *grid* region 7) |#
(define (grid-ref g f n)
(map (lambda (i) (vector-ref g i)) (f n)))
(define (grid-set! g f n ls)
(for-each (lambda (i x) (vector-set! g i x))
(f n) ls))