方案:使用lambda作为参数

时间:2013-10-30 17:44:23

标签: scheme

大家好,对于学校我必须创建一个函数,其中lambda用作参数

喜欢这样:(string(lambda ...)5 40)我们必须填写点

这是我们必须重新发明的函数,常规字符串版本

(define (string decoration n r)            >string decoration is a function that creates a string with either fish or pumpkins hanging on the string
  (define (decorations k)                  >decorations is the recursive function which hangs all the decorations together
    (if (= k 1)
        (decoration r 10)                  > here decoration is to be replaced with either a pumpkin or a fish as stated in the parameters
        (ht-append (decoration r 10)       > ht-append is a function that appends 2 figures Horizontally at the Top
                   (decorations (- k 1)))))
  (hang-by-thread (decorations n)))        > hang by thread is a function that hangs all the decorations at a string

所有的名字都应该是不言自明的,这个功能需要装饰,无论是鱼还是南瓜,都是用线程挂起来的。但鱼有3个参数,南瓜有2个,导致错误。因此,在之前的练习中,我们必须制作一个名为fish-square的额外定义,它仅使用2个参数来制作鱼。现在我们必须实现这个相同的方形鱼,但有一个lambda。非常感谢任何帮助

(define (fish-square wh l)                        > this is the fish square functio which makes a fish but with 2 times the same parameter so it looks like a square
  (vc-append (filled-rectangle 2 l) (fish wh wh)))   > the l is the length of the string that attaches the fish to the string at the top

鱼的功能只是(鱼x y)x使它更长,y使它更高。 南瓜功能只是(南瓜x y)同样的故事

所以我的问题是,如何重写给定的代码,但使用lambda作为参数。 我会上传一张图片,但我的回复不够高:s

2 个答案:

答案 0 :(得分:2)

string过程,因为已经接收过程作为参数(您不必重写它!),decoration可以是任意两个参数用于装饰的功能。现在,当您调用它时,您可以传递一个命名过程,例如:

(define (decoration r n)
  <body>)

(string decoration
        5
        40)

...或者同样容易,你可以像lambda那样在线传递相同的程序,如果我理解正确的话,这就是你应该做的:

(string (lambda (r n)
          <body>)
        5
        40)

只需将<body>替换为您要使用的装饰的实际正文。换句话说:您希望做的更改是在调用时将参数传递给函数的方式,但是您不希望更改函数本身。

答案 1 :(得分:0)

想象一下,你有程序+。它可能是真的。它需要几个参数,但是您需要一个不同的过程,它接受一个并将其添加到已经恒定的值3。

因此,您希望传递+及其应添加的额外信息3。

此类程序的完整定义将是

(define (add3 n)
   (+ 3 n))

这是完整定义的简短形式

(define add3 
   (lambda (n)
      (+ 3 n)))

现在,在传递过程3+时,您实际上只能传递它的定义。这两个也是一样的:

(do-computation add3 data)

(do-computation (lambda (n) (+ 3 n)) data)