Hi all, I am very new to lisp. I have this function (adopted from vacuum agent problem)
(defun find-closest-in-grid (radar type pos-x pos-y)
(labels ((distance (x y)
(+ (abs (- x pos-x))
(abs (- y pos-y)))))
(destructuring-bind (width height)
(array-dimensions radar)
(let ((best nil)
((best-distance (+ width height))))
(loop for x from 0 below width
do (loop for y from 0 below height
do (loop for element in (aref radar x y)
do (when (eql (type-of element) type)
(when (<= (distance x y) best-distance)
(setf best (list x y))
(setf best-distance (distance x y))))))))
best)))
But i wish to convert to (defun find-closest-in-grid (radar type ) with only two parameters while keeping the remaining function the same. How should go about doing it
New to LISP
-
- Posts: 78
- Joined: Mon Dec 01, 2014 12:29 pm
- Contact:
Re: New to LISP
You mean you want the position to be global variables instead of parameters?
-
- Posts: 3
- Joined: Fri Mar 11, 2016 8:30 am
Re: New to LISP
Yes David. Thanks for the great help.
Re: New to LISP
Or you can take more functional approach and return a lambda function so instead of:
you write:
Code: Select all
(defun find-closest-in-grid (radar type pos-x pos-y)
(labels ((distance (x y)
(+ (abs (- x pos-x))
(abs (- y pos-y)))))
(destructuring-bind (width height) (array-dimensions radar)
(let ((best nil)
((best-distance (+ width height))))
(loop for x from 0 below width
do (loop for y from 0 below height
do (loop for element in (aref radar x y)
do (when (eql (type-of element) type)
(when (<= (distance x y) best-distance)
(setf best (list x y))
(setf best-distance (distance x y)))))))
best))))
Code: Select all
(defun get-find-closest-in-grid (pos-x pos-y)
(lambda (radar type)
(labels ((distance (x y)
(+ (abs (- x pos-x))
(abs (- y pos-y)))))
(destructuring-bind (width height) (array-dimensions radar)
(let ((best nil)
((best-distance (+ width height))))
(loop for x from 0 below width
do (loop for y from 0 below height
do (loop for element in (aref radar x y)
do (when (eql (type-of element) type)
(when (<= (distance x y) best-distance)
(setf best (list x y))
(setf best-distance (distance x y)))))))
best)))))
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.