Xiaopei's DokuWiki

These are the good times in your life,
so put on a smile and it'll be alright

User Tools

Site Tools


it:prolog

prolog

  • 注意每句后的点
  • 小写字母开头是原子(atom), 值固定, 类似 Ruby 的 symbol
  • 大写字母或 _ 开头是变量
  • 基本概况, 推论和变量
    friends.prolog
    % 事实
    likes(wallace, cheese).
    likes(grommit, cheese).
    likes(wendolene, sheep).
     
    % 规则(可称作 friend/2)
    friend(X, Y) :- \+(X = Y), likes(X, Z), likes(Y, Z).
    % \+ 执行逻辑取反操作
     
    % 以下操作在 prolog compiler 中:
     
    % 加载文件
    | ?- ['friends.pl'].
    yes
     
    % 问问题:
    | ?- likes(wallace, sheep).
    no
     
    | ?- friend(wallace, grommit).
    yes
  • ; for next solution, a for all solutions, RET to stop. 当使用 ;a 时, 若还有结果返回 yes, 没有则返回 no
  • 继承
    family.prolog
    father('Genghis Khan', 'Tolui').
    father('Tolui', 'Kublai').
     
    ancestor(X, Y) :-
    	father(X, Y).
    ancestor(X, Y) :-
    	father(X, Z), ancestor(Z, Y).
  • 元组, 有序, 定长, (1, 2, 3)
  • 列表, 有序, 变长, [1, 2, 3]
    • 可使用 [Head|Tail] 结构列表, Head 将绑定第一个元素, Tail 将以列表形式绑定剩余元素
    • _ 是通配符, 起忽略作用
    • 使用列表做数学运算
      list_math.prolog
      count(0, []).
      count(Count, [Head|Tail]) :- count(TailCount, Tail), Count is TailCount + 1.
       
      sum(0, []).
      sum(Sum, [Head|Tail]) :- sum(TailSum, Tail), Sum is TailSum + Head.
       
      average(Average, List) :- sum(Sum, List), count(Count, List), Average is Sum/Count.
    • 对列表可使用 prolog 自带的 append 规则: if List3 is List1+List2 then append(List1, List2, List3) is true. 但要注意列表是有序的!
      • 一个 append 的实现
        concatenate.prolog
        concatenate([], List, List).
        concatenate([Head|Tail1], List, [Head|Tail2]) :-
        	concatenate(Tail1, List, Tail2).
  • Fibonacci numbers
    % 普通算法
    fib(0, 0).
    fib(1, 1).
    fib(N, NF) :-
        A is N - 1, B is N - 2,
        fib(A, AF), fib(B, BF),
        NF is AF + BF.
        
    % Tail recursive 算法
    fib(0, A, _, A).
    fib(N, A, B, F) :-
    	N1 is N - 1,
    	Sum is A + B,
    	fib(N1, B, Sum, F).
    fib(N, F) :- fib(N, 0, 1, F).
  • list reverse
    reverse([],[]).
    reverse([H|T],R) :-
    	reverse(T,RT),
    	append(RT,[H],R).
  • find min in list
    min([Head|[]],Head).
    min([Head|Tail],Min) :-
    	min(Tail,X),
    	(X < Head ->
    	 Min is X;
    	 Min is Head).

资料

it/prolog.txt · Last modified: 2013/08/19 07:22 (external edit)