是否有可能在重复计划中的匿名函数时引用?

时间:2015-07-28 19:43:53

标签: scheme

我尝试编写函数,为列表中的每个元素添加一些数字,然后将所有这些项的总和。

 (define (num-to-sumtup num)
  (lambda (tup)
    (cond
     ((null? tup) 0)
     (else (+ (car tup) num (num-to-sumtup ())) ;; here I need to get reference on the inner function

有可能吗?

2 个答案:

答案 0 :(得分:3)

You don't need to make it a anonymous procedure. It may have a name in the scope of num-to-sumtup. Here are some examples of ways to do it. The simples way to do this would be to use the rec syntax which is defined in the SRFI-31.

#!r6rs
(import (rnrs base)
        (srfi :31))

(define (num-to-sumtup num)
  (rec (recur tup)
    (cond
     ((null? tup) 0)
     (else (+ (car tup) num (recur (cdr tup)))))))

((num-to-sumtup 10) '(1 2 3 4 5)) ; ==> 65

You can also do this with define:

(define (num-to-sumtup num)
  (define (sum-list tup)
    (cond
     ((null? tup) 0)
     (else (+ (car tup) num (sum-list (cdr tup))))))

  sum-list); we return the locally named procedure

Using higher order procedures and cut from SRFI-26.

#!r6rs
(import (rnrs base)
        (rnrs lists) ; fold-left
        (srfi :26))  ; cut

(define (num-to-sumtup num)
  (lambda (tup)
    (fold-left (cut + <> <> num) 0 tup)))

答案 1 :(得分:1)

是的,有可能。 num-to-sumtup将一个数字作为参数,并返回一个带有列表的函数。所以你执行它来获取函数,然后执行该函数。

 (define (num-to-sumtup num)
  (lambda (tup)
    (cond
     ((null? tup) 0)
     (else
      (+ (car tup) num ((num-to-sumtup num) (cdr tup)))))))
;Value: num-to-sumtup

((num-to-sumtup 10) '(1 2 3 4 5))
;Value: 65

本着sylwester的回答,这是另一种选择

(define (num-to-sup num)
  (lambda (tup)
    (foldl (lambda (x y) (+ num x y)) 0 tup)))