Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

Scheme functions and lists, multiply,add

i am trying to write 2 functions in scheme, the first would multiply every value in a list by a user specified value, 2nd function would add a number to all the values in the list from previous result. i tried something like that but racket throws an error.

(define test (list 1 1 2 3 5))
(define funca(*(test)(2)))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Scheme we use the map higher-order procedure for applying a function over a list of elements - bear in mind that you can't multiply a list, what we can do is multiply each of its elements . For example, to multiply each of the elements by two do this:

(define test (list 1 1 2 3 5))

(map (lambda (element) (* 2 element))
     test)
=> '(2 2 4 6 10)

Notice how we pass a lambda as parameter to map: that's a function that will get applied to each of the elements in the input list, returning a new list with the results. Similarly if we need to, say, add one to the elements in a list:

(map (lambda (element) (+ 1 element))
     test)

=> '(2 2 3 4 6)

The above examples are hard-coded to multiply by two and to add one. For solving your problem, you just have to put each of the above snippets inside a function and pass along the correct parameters in the right places (left as an exercise for the reader).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...