如何编写基于输入返回"n"个函数的列表的函数 [英] How write a function that returns a list of 'n' functions based on an input

查看:91
本文介绍了如何编写基于输入返回"n"个函数的列表的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个函数,该函数返回一个'n'个函数的列表,每个函数分别将输入增加1、2、3 ... n.

I'm looking to create a function that returns a list of 'n' functions each of which increments the input by 1, 2, 3... n respectively.

我使用DrRacket进行尝试.预期结果样本:

I use DrRacket to try this out. A sample of expected outcome :

> (map (lambda (f) (f 20)) (func-list 5))
(21 22 23 24 25)

我可以用静态方式写下来:

I'm able to write this down in a static-way :

> (define (func-list num)
> (list (lambda (x) (+ x 1)) (lambda (x) (+ x 2)) (lambda (x) (+ x 3)) (lambda (x) (+ x 4)) (lambda (x) (+ x 5)))

此外,对实现也有一些限制:

Also that a few restrictions are placed on implementation :

  1. 仅可以使用'cons'和算术运算
  2. func-list应该仅将一个参数作为输入(在这种情况下,"n"是要返回的函数数)

如果有人可以帮助我,那将是很棒的.预先感谢.

It would be great if somebody can help me out. Thanks in advance.

推荐答案

与其显式地写出列表,一种更好的方法是递归为任意n构造它,如下所示:

Instead of explicitly writing out the list, a better approach would be to recursively construct it for an arbitrary n, as follows:

(define (func-list n)
  (define (func-lst a n)
    (if (> a n)
        empty
        (cons (lambda (x) (+ x a))
              (func-lst (add1 a) n))))
  (func-lst 1 n))

例如:

> (map (lambda (f) (f 20)) (func-list 0))
'()
> (map (lambda (f) (f 20)) (func-list 5))
'(21 22 23 24 25)

这篇关于如何编写基于输入返回"n"个函数的列表的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆