Can Horner's method be implemented in lisp using mapcan
or any other map function?
Here is my implementation without map functions:
(defun Horner (lst x)
(cond
((null (cdr lst)) (car lst))
(t
(Horner
(cons
(+ (* (car lst) x) (cadr lst))
(cddr lst)
)
x
)
)
)
)
You cannot do it with map-like functions because they produce lists and you need the result to be a number.
However, not all is lost --
reduce
to the rescue!
(defun horner (polynomial x)
(reduce (lambda (a b)
(+ (* a x) b))
polynomial :initial-value 0))
Note that this version also handles the 0 polynomial correctly: it
returns 0 when called as (horner () 1)
(replace 1 with any number).
This glitch in your tail-recursive version is easily fixed:
(defun horner (polynomial x)
(if (rest polynomial)
(horner (cons (+ (* (first polynomial) x) (second polynomial))
(cddr polynomial))
x)
(or (first polynomial) 0)))