方案:功能辅助 [英] Scheme:function assistance

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

问题描述

我是 Scheme 的新手,我正在考虑一种方法来递归地对给定列表中的每个数字进行立方,到目前为止,这就是我所拥有的:

i am fairly new to Scheme and,i was thinking of a way to cube every number in a given list recursively so far this is what i have:

(define (cube-it-list lst)
  (cond [(empty? lst) empty]
        [else (cons (cube-it (first lst)) 
                    (cube-it-list (rest lst)))]))

但是每次我执行程序时都会出现错误,我不确定为什么会有人提供帮助或想出更好更有效的方法来做到这一点.

but every time I execute the program i get an error and i'm not sure why that is can anyone help or come up with a better more efficient way to do this.

推荐答案

该函数看起来不错,也许问题出在 cube-it 过程或您调用它的方式上.例如,这有效:

The function looks fine, maybe the problem is in the cube-it procedure or in the way you're calling it. For example, this works:

(define (cube-it x)
  (* x x x))

(define (cube-it-list lst)
  (cond
    [(empty? lst)
     empty]
    [else
     (cons (cube-it (first lst))
           (cube-it-list (rest lst)))]))

(cube-it-list '(1 2 3 4 5))
=> '(1 8 27 64 125)

至于更好更有效的方法",请坚持@svk 的回答和 map超过输入列表,这是解决问题的惯用方法这类问题涉及将函数应用于输入列表中的每个元素,以生成带有结果的输出列表:

As for a "better more efficient way to do this", stick to @svk's answer and map over the input list, it's the idiomatic way to solve this type of problem that involves applying a function to each of the elements in an input list, to produce an output list with the results:

(map cube-it '(1 2 3 4 5))
=> '(1 8 27 64 125)

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

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