This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

loop and let

7 posts · 1628 views

Hi,

I want to eliminate the double-execution of (condition-on a) in the following source code:
(loop for a in L
          when (consp (condition-on a))
          do (return (condition-on a)))
How do I do this?

Re: loop and let

Have you ever heard about variables? ;)
(loop for a in L
         for condition = (condition-on a)
          when (consp condition)
          do (return condition))

Re: loop and let

Yes, but I didn't know how to introduce them syntactically here.

Re: loop and let

Stop, wait. I want the following:
    (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

A couple of ways
(loop for f in g
          as fc = (and (>= f tr) (foo f))
          when (consp fc)
          collect fc)
(let ((results nil))
  (dolist (f g (nreverse results))
    (when (>= f tr)
      (let ((fc (foo f)))
        (when (consp fc) (push fc results)))))
(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.
Need an online wiki database? My Lisp startup http://www.formlis.com combines a wiki with forms and reports.

Re: loop and let

Warren Wilkinson wrote:A couple of ways
(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

I don't know what to tell you, it works on my machine (SBCL 1.0.32) when I run the following:
(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?
Need an online wiki database? My Lisp startup http://www.formlis.com combines a wiki with forms and reports.