Lisp snippets

来源:互联网 发布:oracle查询去重复数据 编辑:程序博客网 时间:2024/06/06 07:49
使用Lisp是因为课程AI的要求,贴出一些自己写的lisp的代码和大家分享,以后自己也可以参考。

1. 读取list中某个给定位置的值
;; retrieve the value at the position pos of a list
;; return a list containing the value if successfully
(defun value_at (lp pos)
  (if  (or (not (listp lp)) (and (null lp) (> pos 0)))
    nil                    
    (if (= pos 0)          
      (if (null lp)        
          nil
          (list (car lp)))
      (value_at (cdr lp) (1- pos)))))

2. 获取list中前n个位置的值。返回值是一个列表
(defun first_nth (lp lastn)
  (if (and (>= lastn 0) (listp lp) (not (null lp)))
    (append (list (car lp)) (first_nth (cdr lp) (1- lastn)))
    ))


3. 获取list的sub list。范围是[firstn, lastn)或者是从firstn到结尾的sublist
;; retrieve a sublist of the list in the range of [firstn, lastn)
(defun extract_list (lp firstn &optional lastn)
  (if (= firstn 0)
    (if (null lastn)
      lp
      (first_nth lp (1- lastn)))
    (if (null lastn)
      (extract_list (cdr lp) (1- firstn))
      (extract_list (cdr lp) (1- firstn) (1- lastn)))))

4. 调换list中的两个位置的值
(defun change_pos (lp pos1 pos2)
  (if (or (null lp) (not (listp lp)))
      nil
      (if (= pos1 pos2)
          lp 
          (if (> pos1 pos2)
              (change_pos lp pos2 pos1)
              (let ((value1 (value_at lp pos1)) 
                    (value2 (value_at lp pos2))) 
                   (append (extract_list lp 0 pos1) 
                           value2 
                           (extract_list lp (1+ pos1) pos2) 
                           value1 
                           (extract_list lp (1+ pos2))))))))



原创粉丝点击