人工智能--合一算法

人工智能合一算法

编写语言:

lisp

运行结果

测试结果
测试结果

带注释的源代码

;; 设置变量表用以判断变量
(setq varlist '(x y z))


;; 合一函数
;; 用例 (unify '(p a b)  '(p x y))
(defun unify(e1 e2) 
  (let (bf f1 f2 t1 t2 s1 s2 g1 g2)
    (cond 
      ;; 当e1或e2为原子或空表时
      ((or (atom e1) (atom e2))
       (when (not (atom e1)) (setq bf e1) (setq e1 e2) (setq e2 bf))
       (cond
         ((equal e1 e2) nil)
         ((and (isvar e1) (contain e2 e1)) 'fail)
         ((isvar e1) (list (list e2 e1)))
         ((isvar e2) (list (list e1 e2)))
         (t 'fail)) )
      ;; 当e1与e2都为列表时
      (t
        (setq f1 (car e1)) (setq t1 (cdr e1))
        (setq f2 (first e2)) (setq t2 (rest e2))
        (setq s1 (unify f1 f2))
        (cond ((equal s1 'fail)  'fail)
              (t 
                (setq g1 (substitution t1 s1))
                (setq g2 (substitution t2 s1))
                (setq s2 (unify g1 g2))
                (if (equal s2 'fail) 'fail (compose s1 s2))))))))


;; 合成函数
;; 用例 (compose '((z x) (a y)) '((b z)))
(defun compose(a b)
  (append (substitution a b) b))


;; 代换函数
;; 代换函数中调用了sub子函数
;; 用例 (substitution '(p x y) '((a x) (b y)))
(defun substitution(e s)
  (loop for item in s do(setq e (sub item e)))
  (return-from substitution e))

(defun sub(s e)
  (let (he ta)
    (setq he (car e))
    (setq ta (cdr e))
    ;; 当e为空表时,递归返回
    (if (null e) (return-from sub nil))
    ;; 否则当e的首元素为原子时
    (if (atom he) 
      ;; 当首元素与要替换的变量相,等时进行替换
      (if (equal he (second s)) (cons (first s) (sub s ta)) (cons he (sub s ta)))
      (cons (sub s he) (sub s ta)))))


;; 包含判断函数
;; 用例 (contain '(f x (g y)) 'y )
(defun contain (e x)
  ;; 当e为原子时
  (when (atom e) (return-from contain t))
  ;; 否则进行递归判断
  (loop for item in e
        if(atom item) do(if (equal item x) (return-from contain t))
        else do(if (contain item x) (return-from contain t)))
  (return-from contain nil))


;; 判断变量函数
;; 用例 (isvar 'x)
(defun isvar(a) 
  ;; 利用变量表来预定义变量
  (if (member a varlist) t nil))

  1. 变量是预定义的, 放在了程序开始处的变量表中. 该程序中认定x,y,z是变量, 其他的字母组成的串作为常量, 并且lisp语言中只存在大写的串, 因为小写的串也会被lisp语言转换成大写的.
  2. 程序中用defun定义的函数都可以放在lisp顶层运行, 共有unify, compose , substitution, sub, isvar五个函数
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值