Prolog
逻辑编程语言,不是通过算法来解决逻辑问题
基本构造单元:事实、规则、查询
常量小写开头,变量大写开头
1/* 事实 */2likes(tom, jack).3likes(teacherma, pony).4likes(jerry, pony).5likes(jerry, teacherma).67/* 规则 */8/* \+ 取反 \+(X = Y) 表示 X 不等于 Y,, 逗号分割子目标,都是真才真 */9friend(X, Y) :- \+(X = Y), likes(X, Z), likes(Y, Z).
1-? friend(teacherma, jerry)2true.34-? likes(jerry, Who).5Who = pony ;6Who = teacherma.
例:地图着色
1color(red).2color(green).3color(blue).45colorify(A,B,C,D,E) :-6 color(A), color(B), color(C), color(D), color(E),7 \+ A=B, \+ A=C, \+ A=D, \+ A=E,8 \+ B=C, \+ C=D, \+ D=E.
1?- colorify(A,B,C,D,E).2A = red,3B = D, D = green,4C = E, E = blue;5A = red,6B = D, D = blue,7C = E, E = green ;8A = green,9B = D, D = red,10C = E, E = blue ;11A = green,12B = D, D = blue,13C = E, E = red ;14A = blue,15B = D, D = red,16C = E, E = green ;17A = blue,18B = D, D = green,19C = E, E = red ;
递归
1father(a, b).2father(b, c).3father(c, d).4father(d, e).56ancestor(X, Y) :- father(X, Y).7ancestor(X, Y) :- father(X, Z), ancestor(Z, Y).
1?- ancestor(a, Who).2Who = b ;3Who = c ;4Who = d ;5Who = e ;6false.
列表长度可变 [1, 2, 3]
,元组长度不可变 (1, 2, 3)
1?- (1, 2, 3) = (1, 2, 3)2true3?- [1, 2, 3] = [1, 2, 3]4true5?- (A, 2, C) = (1, B, 3)6A = 17B = 28C = 39?- [A, 2, C] = [1, B, 3]10A = 111B = 212C = 313?- [a, b, c, d, e] = [_, _| [Head | Tail]]14Head = c15Tail = [d, e]
1count(0, []).2count(Count, [_| Tail]) :- count(TailCount, Tail), Count is TailCount + 1.34sum(0, []).5sum(Total, [Head| Tail]) :- sum(Sum, Tail), Total is Head + Sum.67average(Average, List) :- sum(Sum, List), count(Count, List), Average is Sum / Count.
1append([], List, List).2append([Head| List1], List2, [Head| Tail]) :- append(List1, List2, Tail).
1?- append(L1, L2, [1, 2, 3, 1, 5]).2L1 = [],3L2 = [1, 2, 3, 1, 5] ;4L1 = [1],5L2 = [2, 3, 1, 5] ;6L1 = [1, 2],7L2 = [3, 1, 5] ;8L1 = [1, 2, 3],9L2 = [1, 5] ;10L1 = [1, 2, 3, 1],11L2 = [5] ;12L1 = [1, 2, 3, 1, 5],13L2 = [] ;14false
例:八皇后、数独
feeling
逻辑编程