Newbie lisper looking for hints
andreif_at_mail.dntis.ro
Date: 03/24/05
- Next message: Förster vom Silberwald: "Re: How powerful macros are?"
- Previous message: Harald Hanche-Olsen: "Re: Tim Bray's Mind"
- Next in thread: Joe Marshall: "Re: Newbie lisper looking for hints"
- Reply: Joe Marshall: "Re: Newbie lisper looking for hints"
- Reply: M Jared Finder: "Re: Newbie lisper looking for hints"
- Reply: Simon Alexander: "Re: Newbie lisper looking for hints"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 24 Mar 2005 02:00:35 -0800
Greetings,
Back to my magic-square problem I have written something looking like
this :
(defun test-sum (sum lst)
;; returns (lst) if list element sum is equal to 'sum', NIL otherwise
(if (= (apply #'+ lst) sum)
(list lst)
()))
(defun sublist-n-elements-fixed-sum (n sum0 lst lst0)
(cond
((= n 0) (test-sum sum0 lst0))
(T
(setf acc NIL)
(dolist (x lst acc)
(cond
((<= x sum0)
(setf new-lst (remove x lst))
(setf new-lst0 (append (list x) lst0))
(setf val (sublist-n-elements-fixed-sum (1- n) sum0 new-lst
new-lst0))
(nconc acc (list val))
(print (append '("after call =>") (list val) (list acc)))
)
)
)
)
)
)
if called with:
(sublist-n-elements-fixed-sum 3 15 '(1 2 3 4 5 6 7 8 9) ())
it should return all lists of 3 elements from the list (1 2 3 4 5 6 7 8
9) and the sum of all elements in those list must be 15.
My biggest problem is in the recursive call :
(setf val (sublist-n-elements-fixed-sum (1- n) sum0 new-lst
new-lst0))
(nconc acc (list val))
(print (append '("after call =>") (list val) (list acc)))
I did a (trace ...) on the function and at some point the recursive
call returns a list, val is set to a good value but acc remains still
NIL at the print call which I really don't understand why. I used the
simplest example :
(print (sublist-n-elements-fixed-sum 2 3 '(1 2) ()))
and I get :
1: (SUBLIST-N-ELEMENTS-FIXED-SUM 2 3 (1 2) NIL)
2: (SUBLIST-N-ELEMENTS-FIXED-SUM 1 3 (2) (1))
3: (SUBLIST-N-ELEMENTS-FIXED-SUM 0 3 NIL (2 1))
3: returned ((2 1))
("after call =>" ((2 1)) NIL)
2: returned NIL
("after call =>" NIL NIL)
2: (SUBLIST-N-ELEMENTS-FIXED-SUM 1 3 (1) (2))
3: (SUBLIST-N-ELEMENTS-FIXED-SUM 0 3 NIL (1 2))
3: returned ((1 2))
("after call =>" ((1 2)) NIL)
2: returned NIL
("after call =>" NIL NIL)
1: returned NIL
NIL
Something is wrong here but I don't see why, I tried replacing (setf
acc ()) with (let ((acc ()) ...) but same result.
Any hints on what I might be doing wrong ?
Thanks,
Andrei
- Next message: Förster vom Silberwald: "Re: How powerful macros are?"
- Previous message: Harald Hanche-Olsen: "Re: Tim Bray's Mind"
- Next in thread: Joe Marshall: "Re: Newbie lisper looking for hints"
- Reply: Joe Marshall: "Re: Newbie lisper looking for hints"
- Reply: M Jared Finder: "Re: Newbie lisper looking for hints"
- Reply: Simon Alexander: "Re: Newbie lisper looking for hints"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|