Discussion:
Lisp Function Problem
(too old to reply)
Robert L.
2019-12-01 07:20:24 UTC
Permalink
Write a Function 'total' that takes an orderd list ie.
((itemA quantityA costA)(itemB quantityB costB)....)
but returns a list giving the total cost plus the overall cost.
LISP>(total'((book 2 10)(pen 3 2)(notepad 1 12)))
((BOOK 20)(PEN 6)(NOTEPAD 12)(TOTAL 38))
;; map applying function
(define (map@ func xs)
(map (lambda (x) (apply func x)) xs))

(define (total items)
(let ((tmp (map@ (lambda (s q p) `(,s ,(* q p))) items)))
`(,@tmp (total ,(apply + (map cadr tmp))))))


(total '((book 2 10) (pen 3 2) (notepad 1 12)))
===>
((book 20) (pen 6) (notepad 12) (total 38))
Robert L.
2019-12-01 15:06:28 UTC
Permalink
Post by Robert L.
Write a Function 'total' that takes an orderd list ie.
((itemA quantityA costA)(itemB quantityB costB)....)
but returns a list giving the total cost plus the overall cost.
LISP>(total'((book 2 10)(pen 3 2)(notepad 1 12)))
((BOOK 20)(PEN 6)(NOTEPAD 12)(TOTAL 38))
;; map applying function
(map (lambda (x) (apply func x)) xs))
(define (total items)
(total '((book 2 10) (pen 3 2) (notepad 1 12)))
===>
((book 20) (pen 6) (notepad 12) (total 38))
(define-syntax map@
(syntax-rules ()
[(map@ ((params ...) stuff ...) xs)
(map (lambda (x) (apply (lambda (params ...) stuff ...) x)) xs)]
[(map@ func xs)
(map (lambda (x) (apply func x)) xs)]))

(define (total items)
(let ((tmp (map@ ((s q p) `(,s ,(* q p))) items)))
`(,@tmp (total ,(apply + (map cadr tmp))))))
Robert L.
2019-12-07 02:52:41 UTC
Permalink
Post by Robert L.
Write a Function 'total' that takes an orderd list ie.
((itemA quantityA costA)(itemB quantityB costB)....)
but returns a list giving the total cost plus the overall cost.
LISP>(total'((book 2 10)(pen 3 2)(notepad 1 12)))
((BOOK 20)(PEN 6)(NOTEPAD 12)(TOTAL 38))
;; map applying function
(map (lambda (x) (apply func x)) xs))
(define (total items)
(total '((book 2 10) (pen 3 2) (notepad 1 12)))
===>
((book 20) (pen 6) (notepad 12) (total 38))
;; map applying function
(define (map@ func xs)
(map (lambda (x) (apply func x)) xs))

(define (total items)
(let* ((names (map car items))
(totals (map@ * (map cdr items)))
(grand (apply + totals)))
(append (map list names totals) `((total ,grand)))))

(total '((book 2 10) (pen 3 2) (notepad 1 12)))
===>
((book 20) (pen 6) (notepad 12) (total 38))

Loading...