开发者

trying to make a scheme procedure

trying to make a scheme procedure called make-odd-mapper! its supposed to be a procedure that takes one input, a procedure, and produces a procedure as an output

ex:

(define i4 (mlist 10 2 30 4))

(i4)

{10 2 30 4}

((make-odd-mapper! add-one) i4)

i4

{11 2 31 4}

I know the problem needs to mutate the input list and that set-mcar! and void are apart of it......could anyone giv开发者_JAVA百科e me some reasonable lines of code to solve this? It would be useful in case anyone was wondering about mutation.....and using it to create a procedure that makes a procedure as its output....


Well, the problem as posed, to put it shortly, is impossible. The reason is, if it were possible, then you could have an expression:

(make-odd-mapper! add-one)

and this would be a function of a function, created by partial application. However, this function would have to modify its operand, and this can only be done by a macro. Therefore, the result of that function would be a macro, which is impossible, because macros don't exist as values. However, by a slight change in the definition of make-odd-mapper! it is possible to do something slightly different. In this case, you would use it exactly as in the original question, except that instead of saying

((make-odd-mapper! add-one) i4)

You would say

(make-odd-mapper! add-one i4)

Here is the code that does it this way:

;;; Applies its argument to every other element of a list.
(define map-every-other
  (lambda (function lis)
    (let map-every-other ((function function) (lis lis) (acc '()) (other #t))
      (if (null? lis)
      acc
      (map-every-other
       function
       (cdr lis)
       (append acc (list (if other (function (car lis)) (car lis))))
       (not other))))))

;;; This function does the odd mapping, but returns
;;; the new function instead of mutating the original.
(define make-odd-mapper
  (lambda (function-to-apply)
    (lambda (function)
      (lambda ()
        (map-every-other function-to-apply (function))))))

;;; This macro mutates the original function by using make-odd-mapper
(define-syntax make-odd-mapper!
  (syntax-rules ()
    ((_ function-to-apply function)
     (begin
       (set! function
         ((make-odd-mapper function-to-apply) function))))))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜