Implementation of the variation map function in the circuit

As you can see in the example below, the map function in Scheme is a variational function.

> (map (lambda (number1 number2)
     (+ number1 number2))
   '(1 2 3 4)
   '(10 100 1000 10000))
'(11 102 1003 10004)

I want to implement this variational option, but I managed to find an implementation of two arguments:

(define (map f lst)
   (if (null? lst)
       '()
       (cons (f (car lst)) (map f (cdr lst)))))

Can someone help me implement a variable map function?

+3
source share
2 answers

In the diagram, you can write a function like (lambda x ...), and in this case it xbinds to the entire list of arguments or uses the wrong lambda list, for example (lambda (a b c . ds) ...), which takes at least three arguments and binds dsto the list of remaining arguments. Then the code you are trying to write will be similar to (I write in the R5RS scheme):

(define (my-map function list1 . more-lists)
  (define (some? function list)
    ;; returns #f if (function x) returns #t for 
    ;; some x in the list
    (and (pair? list)
         (or (function (car list))
             (some? function (cdr list)))))
  (define (map1 function list)
    ;; non-variadic map.  Returns a list whose elements are
    ;; the result of calling function with corresponding
    ;; elements of list
    (if (null? list)
        '()
        (cons (function (car list))
              (map1 function (cdr list)))))
  ;; Variadic map implementation terminates
  ;; when any of the argument lists is empty
  (let ((lists (cons list1 more-lists)))
    (if (some? null? lists)
        '()
        (cons (apply function (map1 car lists))
              (apply my-map function (map1 cdr lists))))))

:

(my-map + '(0 2 5) '(1 2 3))
;=> (1 4 8)

, map ( map1), (map1 car lists), function , (map1 cdr lists) , . map ( my-map), map.

+8

, , case-lambda, , . :

(define my-map
  (case-lambda
   ((func list) …)
   ((func list1 list2) …)
   (…)
   ((func . lists) …)))

, . case-lambda " ", ( ):

(define my-map
  (lambda args ;; illustration only, implementations vary.
    (apply (let ((len (length args)))
             (cond ((= 2 len) (lambda (func list) …))
                   …))
           args)))
+2

All Articles