Search code examples
listcommon-lispgreatest-common-divisor

GCD of a non linear list Lisp


How can I get the GCD of a non-linear list using Map functions in Common Lisp?

defun gcd (a b)
    (cond
      ((eq b 0) a)
      (t (gcd b (mod a b)))))

(defun gcdall (l)
    (cond
        ((null l) nil)
        (t (...))
)
)

I don't quite understand how to use map-functions, so any help/hints would be great. Thanks!


Solution

  • If I understand what you want correctly, that's easy enough:

    (defun nested-gcd (list)
      (reduce #'gcd list :key (lambda (elt)
                                (if (consp elt)
                                    (nested-gcd elt)
                                  elt))))