Sum odd elements of a list
Java Version
//// P0: Compute the sum of the odd elements of a list.
class Cons extends Object {
int car;
Cons cdr;
Cons(int car, Cons cdr) {
this.car = car;
this.cdr = cdr;
}
public static boolean isNull(Object x) { return x == null; }
public int car() { return this.car; }
public Cons cdr() { return this.cdr; }
}
class Puzzler_0 extends Object {
public static int sum_odd(Cons es) {
int sum = 0;
while(!Cons.isNull(es)) {
int e = es.car();
if (e%2 == 1) sum = sum + e;
es = es.cdr();
}
return sum;
}
}
Lisp Version
;;; 0: Compute the sum of the odd elements of a list
(defvar L '(2 9 3 8 4 7))
(defun main ()
(print (sum-odd '(2 9 3 8 4 7))))
(defun sum-odd (elements)
(let ((sum 0))
(dolist (e elements)
(if (oddp e) (setq sum (+ sum e))))
(sum-odd sum)))