方案中的功能构建器 [英] A function builder in scheme

查看:102
本文介绍了方案中的功能构建器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该构建的函数应该将数字列表作为参数,并给出一个函数作为输出,其功能如下:如果列表中的数字为正数,则将其添加,如果它是负数乘以它,如果它是0,则将数字平方.

A function I'm supposed to build is supposed to take in a list of numbers as a parameter, and give a single function as an output that does as follows: If the number in the list is a positive number, add it, if it is negative multiply by it, and if it is 0, square the number.

例如,如果我传入(4 -1 0),它应该返回一个函数,该函数接受单个参数,将其加4,再乘以-1,对其求平方,然后返回.

For example, if I pass in (4 -1 0), it should return a function that takes in a single parameter, adds 4 to it, multiplies it by -1, squares it, and returns that.

我认为自己走在正确的轨道上,但是现在我变得非常困惑.我不一定要寻找解决方案,但是任何帮助实现该目标的方法都将是惊人的.这是我到目前为止的内容:

I think I'm on the right track, but I'm getting seriously confused at this point. I'm not necessarily looking for a solution, but any help getting there would be amazing. Here's what I have so far:

(define (buildseries L)
  (define (a x) 
    (lambda (y) (+ x y)))
  (define (m x) 
    (lambda (y) (* x y)))
  (define (s x) 
    (lambda (x) (* x x)))
  (define (funcfind d)
    (cond
     [(null? d) (a 0)]
     [(> d 0) (a d)]
     [(= d 0) (s d)]
     [(< d 0) (m d)]))
  (funcfind (first L)))

((buildseries '(2)) 2)

我不知道如何构建一个由其他功能组合而成的功能……只是在这里感到迷茫.

I don't know how to build a function that is a composite of other functions... Just feeling lost here.

推荐答案

乔恩的答案非常好.您应该尽可能地实现它.如果需要,您也可以在这里参考我的答案(这与乔恩的做法不符,因为我在乔恩发布他的大部分答案之前就写下了我的答案):

Jon's answer is very good. You should try to implement it as much as you can. If you need to, you can also refer to my answer here (which doesn't follow Jon's approach since I wrote most of my answer before he posted his):

(define (fun nums)
  (lambda (x)
    (let loop ((nums nums)
               (value x))
      (if (null? nums) value
          (let ((num (car nums))
                (rest (cdr nums)))
            (cond ((positive? num)
                   (loop rest (+ value num)))
                  ((negative? num)
                   (loop rest (* value num)))
                  ((zero? num)
                   (loop rest (* value value)))))))))

您应该研究它以了解其工作原理,然后使用完全不同的方法来编写自己的版本,例如Jon关于使用compose的想法. :-)

You should study it to see how it works, then write your own version using a completely different approach, like Jon's idea about using compose. :-)

我编写的功能可以进一步简化:使用SRFI 1的fold,您可以执行以下操作:

The function I wrote can be simplified further: using SRFI 1's fold, you can do this:

(define (fun nums)
  (define (step num value)
    (cond ((positive? num) (+ value num))
          ((negative? num) (* value num))
          (else (* value value))))
  (lambda (x)
    (fold step x nums)))

这篇关于方案中的功能构建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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