Page 1 of 1
loop and let
Posted: Wed Nov 24, 2010 12:21 pm
by imba
Hi,
I want to eliminate the double-execution of (condition-on a) in the following source code:
Code: Select all
(loop for a in L
when (consp (condition-on a))
do (return (condition-on a)))
How do I do this?
Re: loop and let
Posted: Wed Nov 24, 2010 12:41 pm
by gugamilare
Have you ever heard about variables?
Code: Select all
(loop for a in L
for condition = (condition-on a)
when (consp condition)
do (return condition))
Re: loop and let
Posted: Wed Nov 24, 2010 12:50 pm
by imba
Yes, but I didn't know how to introduce them syntactically here.
Re: loop and let
Posted: Wed Nov 24, 2010 1:25 pm
by imba
Stop, wait. I want the following:
Code: Select all
(loop for f in g
when (>= f tr)
for fc = (foo f)
when (consp fc)
collecting fc))
How do I correct this code? It is importent that fc is only evaluated when ">= f tr" is true.
Re: loop and let
Posted: Wed Nov 24, 2010 1:41 pm
by Warren Wilkinson
A couple of ways
Code: Select all
(loop for f in g
as fc = (and (>= f tr) (foo f))
when (consp fc)
collect fc)
Code: Select all
(let ((results nil))
(dolist (f g (nreverse results))
(when (>= f tr)
(let ((fc (foo f)))
(when (consp fc) (push fc results)))))
Code: Select all
(defun process (f)
(when (> f tr)
(let ((fc (foo f)))
(and (consp fc) (list fc)))))
(mapcan #'process g)
There are other possible ways too; take whichever most closely resembles how you think about the problem domain.
Re: loop and let
Posted: Wed Nov 24, 2010 2:03 pm
by imba
Warren Wilkinson wrote:A couple of ways
Code: Select all
(loop for f in g
as fc = (and (>= f tr) (foo f))
when (consp fc)
collect fc)
Thanks, but with this I get "Error: The variable WHEN is unbound."
EDIT: I finally got it working! Thanks!
Re: loop and let
Posted: Wed Nov 24, 2010 3:54 pm
by Warren Wilkinson
I don't know what to tell you, it works on my machine (SBCL 1.0.32) when I run the following:
Code: Select all
(defun foo (f) (if (evenp f) (list f) f))
(loop for f in '(1 2 3 4)
as fc = (and (>= f 2) (foo f))
when (consp fc)
collect fc)
;; gives ==> ((2) (4))
You could try replacing the word 'when' with 'if', what implementation of Lisp are you using?