I was wondering, how do you check if every element in a list is an integer or not? I can check the first element by using (integer? (car list), but if I do (integer? (cdr list), it always returns false (#f) because the whole of the last part of the list is not an integer as a group. In this case let's say list is defined as. (define list '(1 2 5 4 5 3))
asked Jul 23, 2012 at 21:01 137 1 1 gold badge 3 3 silver badges 11 11 bronze badges (define get-integers (lambda (x) (if (null? x) "All elements of list are integers" (if (integer? (car x)) (get-integers (cdr x)) "Not all elements are an integer"))))
answered Jul 23, 2012 at 21:57
2,725 6 6 gold badges 39 39 silver badges 57 57 bronze badges
Returning strings instead of booleans? using nested if s instead of cond ? This solution is not very idiomatic.
Commented Jul 24, 2012 at 4:24 It's better for clarity as this is for showing the logic behind this approach. Commented Mar 8, 2018 at 0:36Practical Schemes provide functions for doing tests across whole sequences. An application of the andmap function, for example, would be appropriate. Racket provides a for/and to do something similar. If you really needed to write out the loop by hand, you'll be using recursion.
answered Jul 23, 2012 at 21:18 12k 1 1 gold badge 37 37 silver badges 45 45 bronze badgesWhat you need to do is test each element in the list to see if it satisfies a condition (being an integer, in this case). When you evaluate (integer? (car list)) on a list of integers, you're checking if the first element in the list is an integer, and that's fine. But the expression (integer? (cdr list)) tests if a list is an integer (because cdr returns a list), and that won't work - you need to test the next element in the list, and the next, and so on until the list is empty.
There are several ways to do the above, the most straightforward would be to recur on the list testing each element in turn, returning false if a non-integer element was found or true if all the list was consumed without finding a non-integer element, like this:
(define (all-integers? lst) (cond ((null? lst) #t) ((not (integer? (car lst))) #f) (else (all-integers? (cdr lst)))))
A more practical approach would be to use a built-in procedure, like this:
(andmap integer? lst)
andmap will check if all the elements in lst evaluate to true for the given predicate. For example:
(andmap integer? '(1 2 3)) > #t (andmap integer? '(1 "x" 3)) > #f