简体   繁体   中英

How can I define x as a list of integers to evaluate a polynomial for all elements in x?

The polynomial:

(modulo (+ (expt x 2) 2) 5)

I want to do something like

(define x <list of integers like 0, ..., 10>)

It should then output the result(s) like:

3
1
1
3
...

Do I have to write a separate method to get this working or does Scheme have something built-in?

I am not sure what you are asking, but if you want to construct a list of incrementing integers, to each element of which you can apply your polynomial function, SRFI-1 has the iota procedure. So

(iota 10)

will construct a list of 10 integers in the range 0 to 9. iota optionally takes additional start and step arguments. To apply the polynomial function to each integer and construct a new list of the results, you can use map.

The way you have it written won't work. In you're polynoimial your taking expt of x directly, which if you define it to be a list, will result in a run-time error.

(map (lambda (x) (modulo (+ (expt x 2) 2) 5)) (iota 11 1 1))

;Value 2: (3 1 1 3 2 3 1 1 3 2 3)

What I did was wrap up your polynomial as an anonymous function, and used it as an argument to map. The second argument (iota count start step) generates a list of length count starting at start and proceeding by and addition of step . start and step are optional argument defaulting to 0 and 1 respectively.

Map is a higher order function which accepts a function as it's first argument and one or more lists afterwards. To simplify thing's I'll ignore cases where more than one list is use. The new list meets the condition that any given element is the result of applying the function to the corresponting element of the original list.

(map f (x y z ...)) -> ((f x) (f y) (f z) ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM