我在Lisp中有这个功能:
(defun AddtoQueue (queue method)
(cond
( (eq method 'DFS) (append (growPath (car queue) (findCh (caar queue))) (cdr queue) ) )
( (eq method 'BFS) (append (cdr queue) (growPath (car queue)(findCh (caar queue))) ) )
( (eq method 'A) (SORT (append (cdr queue) (growPath (car queue) (findCh (caar queue)) ) ) #'> :key #'pathLength ) )
(T "not implemented")
)
)
我必须使用自定义函数(此处命名为pathLength
)对列表进行排序。我阅读了有关sort
的lisp文档,但我无法理解。我的问题是我究竟在为比较功能提供什么?
比较功能:
(defun pathLength(point)
;;distance from origin point
(setq x (- (length queue) 1) )
;;distance from end(manhattan distance) by subtracting the coords.
;;calc lists is adding or subtracting lists.
(setq y (calcLists (cadr (assoc (car point) coords)) (cadr (assoc terminal coords)) 'sub ) )
(setq y (+ (car y) (cadr y) ) )
;;sum of distance from start and end.
(+ x y)
)
答案 0 :(得分:4)
比较函数(在本例中为>
)获取两个参数(两个元素进行比较)。在进行比较之前,参数将通过关键函数(pathLength
)。您可以使用TRACE
查看调用的函数。例如:
(trace >)
;=> (>)
(sort (list 4 5 1) #'>)
; 0: (> 5 4)
; 0: > returned T
; 0: (> 1 4)
; 0: > returned NIL
;=> (5 4 1)
(trace 1+)
;=> (1+)
(sort (list 4 5 1) #'> :key #'1+)
; 0: (1+ 5)
; 0: 1+ returned 6
; 0: (1+ 4)
; 0: 1+ returned 5
; 0: (> 6 5)
; 0: > returned T
; 0: (1+ 1)
; 0: 1+ returned 2
; 0: (1+ 4)
; 0: 1+ returned 5
; 0: (> 2 5)
; 0: > returned NIL
;=> (5 4 1)
(untrace > 1+)
;=> T
关于您的代码的一些评论。
add-to-queue
代替AddtoQueue
。名称(符号)通常会自动转换为大写(并在注释等中写入),但在编写实际代码时,应使用小写。LET
而不是SETQ
来定义局部变量。COND
中的ADD-TO-QUEUE
仅将METHOD
EQ
与PATH-LENGTH
进行比较,因此CASE
更适合此任务。QUEUE
正在使用ADD-TO-QUEUE
的本地变量TERMINAL
。您需要使用FLET
。COORDS
和*TERMINAL*
的变量,这些变量似乎不存在于任何一个函数中。如果这些是全局(特殊)变量(应使用DEFVAR
or DEFPARAMETER
定义),则应在名称周围添加耳罩(星号)以显示:*COORDS*
,(defun add-to-queue (queue method)
(flet ((path-length (point)
(let* ((x (1- (length queue)))
;; It's better to use FIRST and SECOND instead of CAR and
;; CADR when dealing with lists.
(temp (calc-lists (second (assoc (car point) *coords*))
(second (assoc *terminal* *coords*))
'sub))
(y (+ (first temp) (second temp))))
(+ x y))))
(case method
(DFS
;; Consider using full words for function names. So
;; FIND-CHARACTER, assuming that's what CH means.
(append (grow-path (car queue)
(find-ch (caar queue)))
(cdr queue)))
(BFS
(append (cdr queue)
(grow-path (car queue)
(find-ch (caar queue)))))
(A
(sort (append (cdr queue)
(grow-path (car queue)
(find-ch (caar queue))))
#'> :key #'path-length))
;; You could use `ECASE` to automatically signal an error
;; if METHOD doesn't match any of the cases.
(otherwise "not implemented"))))
。如果没有完整的代码,我无法测试,但代码看起来应该是这样的:
class