untitleddeltitnu
untitleddeltitnu

Reputation: 21

Transforming a function into a list in Drracket

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.

Upvotes: 1

Views: 305

Answers (1)

ben rudgers
ben rudgers

Reputation: 3669

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)

Upvotes: 1

Related Questions