Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...