Scheme:function assistance

有些话、适合烂在心里 提交于 2019-12-12 03:29:31

问题


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.


回答1:


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)

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)



回答2:


Have you defined the function cube-it? When I did, your code worked for me.

In any case, there is a construct in Scheme for precisely this sort of thing: making one list out of another by applying a transformation to each element. It's called map:

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

You've essentially reinvented it here, except map is not limited to a single transformation operation - you pass it the function you want to use as its first argument.

(Note, if you've been specifically told to implement a recursive solution, you should stick with your original code. map will use recursion internally, but using map means your own code doesn't need to involve any recursion for this case.)



来源:https://stackoverflow.com/questions/15649352/schemefunction-assistance

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!