i'm doing lisp exercises using functions mapcar , apply. i'm dealing matrixes, , have sum rows , columns. column have:
(apply #'mapcar #'+ matrix) that works. since know how transpose matrix, can exact same thing rows right? right, be:
(apply #'mapcar #'+ (apply #'mapcar #'list matrix)) but i'm not happy with that. want sum row directly, did mapcar of apply:
(mapcar #'apply #'+ matrix) that doesn't work , don't know why. error
the value #(function +) not of type list. [condition of type type-error]
for me, every list inside matrix, , apply sum in each one. cannot make mapcar of apply? if no, why not? there way sum rows of matrix using mapcar , apply?
ps: i'm using lispstick compile , matrix list of lists. example
((1 1 1) (2 2 2) (3 3 3)) for 3x3 matrix.
your error
the error got mapcar expects lists arguments after 1st one, , finds function + instead.
solution
what need partial application of apply +, i.e.,
(defparameter matrix '((1 1 1) (2 2 2) (3 3 3))) (mapcar (lambda (l) (apply #'+ l)) matrix) ==> (3 6 9) you can define function that:
(defun partial-application (f &rest some-args) (lambda (&rest more-args) (apply f (append some-args more-args)))) (funcall (partial-application #'+ 4) 5) ==> 9 (funcall (partial-application #'+ 1 2) 3 4 5) ==> 15 now can use instead of lambda:
(mapcar (partial-application #'apply #'+) matrix) ==> (3 6 9) notes:
(lambda (l) (apply #'+ l)),(partial-application #'apply #'+)merely compute sum of list, , can defined in many different ways discussed elsewhere.appendcannot safely replaced non-consing versonnconcbecausesome-argsis not guaranteed fresh:
the value of rest parameter permitted, not required, share structure last argument
apply.
Comments
Post a Comment