Scheme functions and lists, multiply,add

别来无恙 提交于 2019-12-25 20:05:06

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/25729505/scheme-functions-and-lists-multiply-add

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