2015-11-26 41 views
0

我有一个像下面的代码。它返回列表,(((1 . 2) (1 . 0)) ((1 . 2) (1 . 1)) ((1 . 2) (1 . 3)) ((1 . 2) (1 . 4)) ((1 . 2) (1 . 5)) ((1 . 2) (1 . 6)) ((1 . 2) (1 . 7)) ((1 . 2) (0 . 2)) ((1 . 2) (2 . 2)))LISP。创建对的列表

我不知道如果我能在路上改写generHod功能,使其返回列表像((1.2 1.0) (3.4 4.2) (1.3 1.3)...)

(setf hod '()) 

(defun generHod (CurrX CurrY) 
    (dotimes (y 8) 
     (if (/= y CurrY) 
      (setf hod (append hod (list (append (list (cons CurrX CurrY))(list (cons CurrX y)))))) 
     ) 
    ) 

    (dotimes (x 8) 
     (if (/= x CurrX) 
      (setf hod (append hod (list (append (list (cons CurrX CurrY))(list (cons x CurrY)))))) 
     ) 
    ) 

) 
+0

所有这些附加业务:不良作风。 –

+0

你提供什么解决方案?不幸的是,我并没有意识到不同的lisp函数可以使它更容易。 –

+2

我可以为您提供一个很好的免费下载介绍性的Lisp书籍,其中介绍了基本知识:https://www.cs.cmu.edu/~dst/LispBook/index.html –

回答

1

首先:

(setf hod '()) 

这是一个糟糕的方式来定义一个全局变量;尝试

(defparameter hod()) 

但为什么要使用全局变量呢?该函数可以构造一个新列表并返回它。如果调用者想要将其粘贴到全局变量中,则由调用者决定;这与该功能的操作无关。

(defun generHod ...) 

语法generHod是不是从Common Lisp中GENERHODgenerhod区分,在默认readtable。所有这些令牌都会产生相同的符号。最好不要在Lisp标识符中播放混合大小写的游戏;如果你想要多个单词,请输入gen-hod。通常generate一律缩写为英语黑客的gen,而不是gener。例如,请参阅Common Lisp中的gensym函数。

在你的功能,有一个完全是多余的append

(append 
    (list (cons CurrX CurrY)) 
    (list (cons CurrX y)))) 

模式(append (list X0) (list X1) ... (list XN))可以改写(list X0 X1 ... XN)。你只是将多余的事物列表添加到一起来制作一个列表,而不是仅仅列出事物。

要想从整数值到浮点,该float功能可以使用,而loop宏提供了一个成语迭代和收集物品:

(defun gen-hod (curr-x curr-y) 
    (let ((cxy (list (float curr-x) (float curr-y)))) ;; allocate just once! 
    (nconc ;; destructive append: use with care 
     (loop for y from 1 to 8 
      when (/= y curr-y) 
       append (list cxy (list (float curr-x) (float y)))) 
     (loop for x from 1 to 8 
      when (/= x curr-x) 
       append (list cxy (list (float x) (float curr-y)))))))