Scheme:function assistance

2019-09-15 13:23发布

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.

标签: scheme
2条回答
家丑人穷心不美
2楼-- · 2019-09-15 13:58

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.)

查看更多
Rolldiameter
3楼-- · 2019-09-15 14:09

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)
查看更多
登录 后发表回答