Reputation: 2362
I try to write function which add some number to every element in the list and then makes sum of all this terms.
(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
is it possible?
Upvotes: 1
Views: 66
Reputation: 1189
Yes, it is possible. num-to-sumtup
Takes a number as argument, and returns a function, that takes a list. So you execute it to get the function, and then execute that function.
(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
In the spirit of sylwester's answer here's another option
(define (num-to-sup num)
(lambda (tup)
(foldl (lambda (x y) (+ num x y)) 0 tup)))
Upvotes: 1
Reputation: 48745
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)))
Upvotes: 3