首页 > 其他分享 >Prolog

Prolog

时间:2023-03-18 18:12:15浏览次数:41  
标签:apple T2 list Syntax fruit location Basic kitchen Prolog

1. Run Prolog

  1. file name: test.pl
  2. go to the location of the test.pl in terminal
  3. input swipl
  4. input [test].(remember '.')
  5. do sth
  6. if you want to halt the file, input halt
  • e.g.
    image

2. Facts

  1. comment: type '%': % This is the syntax for comments
  2. facts
    1. fact: pred(arg1, arg2, ..., argn).
    2. arg: integer, atom, string begin with lower letter etc
    3. variable: item begin with '_' or UPPER LETTER, structure etc
    4. e.g.
      father('David', 'John').    % remember '.' at the end 
      room(a).
      

3. Simple Query

  1. ?-: the prompt for the interpreter

  2. query: type pred(something)

    1. if exist answer, return the answer; if you want more answer, type ;
    2. e.g.
      room(a).
      room(b).
      
      image
  3. query principle inside

    1. prolog will match user's target to find the answer; when input ;, it will redo (release the variable first and start the search from the last token)
    2. prolog's target has four ports to control the processes
      1. call: find the clause
      2. exit: target matched successfully, mark the success clause, and bind the variable
      3. redo: release the variable first and start the search from the last token
      4. fail: can not find more success clause
  4. debug: input debug

  5. trace: input trace

    • e.g.
      room(a).
      room(b).
      room(c).
      
      image

4. Hybrid Query

  1. hybrid query: input more query like:

    location(apple, kitchen).
    location(trash, kitchen).
    edible(apple).
    

    image

  2. some interval predicate

    1. write(1 arg): print some string
    2. nl: print an enter
    3. tab(1 arg: n): print n \space
    • e.g.image
      here is the traceimage

5. Rules

  1. rule: head :- body, head is predicate, :- means "if", body is target

    • e.g.
    location(apple, kitchen).
    location(trash, kitchen).
    edible(apple).
    
    where_food(X, Y) :- location(X, Y), edible(X).
    

    result:
    image

  2. append more rules: we can append more rules to define a predicate

    • e.g.
    location(apple, kitchen).
    location(burger, kitchen).
    location(trash, kitchen).
    edible(apple).
    yummy(burger).
    where_food(X, Y) :- location(X, Y), edible(X).
    where_food(X, Y) :- location(X, Y), yummy(X).
    

    image

  3. rules basic principle: in fact rules are multiple layers of query. we can see the trace of last instance: image

6. Arithmetic

  1. math expression: X is expression
    image

  2. operation

    1. +, -, *, /
    2. >, <, >=, =<image
  3. use in rules

    • e.g.
    c_to_f(C, F) :- F is C * 9 / 5 + 32.
    

    image

7. Data Management

  1. asserta & assert

    1. asserta(X): it will append X to the beginning of the dynamic database
    2. assert(X): it will append X to the end of the dynamic database
    3. dynamic pred/arg_size: if you want to use asserta & assert, please type dynamic pred/arg_size to run at the front of the program, which allows pred can be modified dynamically
    • e.g.
    fruit(apple).
    fruit(watermelon).
    

    image

  2. retract(X): remove X from dynamic database(remember dynamic)image

  3. use in rules

    fruit(apple).
    fruit(watermelon).
    fruit(tomato).
    
    is_fruit(X) :- fruit(X).
    is_fruit(X) :- write('NO FRUIT NOW!'), nl, fail.
    
    remove(X) :- retract(fruit(X)).
    

    image

8. Recursion

  1. recursion:

    • e.g.
      location(envelope, desk).
      location(stamp, envelope).
      location(key, envelope).
      
      is_contained_in(T1, T2) :- location(T1, T2).
      is_contained_in(T1, T2) :- location(X, T2), is_contained_in(T1, X).
      
      image
  2. recursion basic principle image

  3. Which is faster?

    1. is_contained_in(T1,T2):- location(X,T2), is_contained_in(T1,X).
    2. is_contained_in(T1,T2):- location(T1,X), is_contained_in(X,T2).
    • if we ask is_contained_in(X, desk), 1. is faster!

9. Unification

  1. unification

    1. variable & any items
    2. original item & original item(atom or integer): when they equal
    3. structure & structure: when each corresponding parameter of two structures can be associated
  2. = (arg1, arg2) or arg1 = arg2

    1. notice: = is Unification

    2. e.g. image

    3. variable unification image image

    4. if the values of the variables conflict in both bindings, it will failimage

    5. anonymous variable _: it will not bind any values image

  3. difference between unification and math expression: unification will not compute, but is will do image

10. Data Structure

  1. structure: functor(arg1, arg2, ...)

    % object(name, color, size, amount)
    location(object(candle, red, small, 1), kitchen).
    location(object(apple, red, small, 1), kitchen).
    location(object(apple, green, small, 1), kitchen).
    location(object(table, blue, big, 50), kitchen).
    

    image

  2. nested structure

    location(object(table, blue, dimension(1, 2, 3), 50), kitchen).
    

    image

11. List

  1. List: [obj1, obj2, ...]

  2. empty list: [] or nil

    % loc_list(nil, hall).
    loc_list([], hall).
    loc_list([apple, banana, orange], kitchen).
    

    image

  3. head and tail

    1. [a|[b, c, d]] = [a, b, c, d], a is head, [b ,c ,d] is tail. we use | to divide them, behind | is a list image

    2. we can use | at other place image

    3. nil can not match [H|T], which can be used in recursion bounds checking image

    4. list basic principle: '[|]'(head, tail) = (head | tail), in fact | is a predicate; we can use display() to see it. image

  4. member(obj, list)

    1. we can use member to see obj is in the list or not. image

    2. member basic principle

      member(H, [H | T]).   % in head ?
      member(X, [H | T]) :- member(X, T).   % in tail ?
      
  5. append(list1, list2, dest)

    1. connect list1 and list2 to be a new list dest image

    2. append basic principle

      append([], X, X).
      append([H | T1], X, [H | T2]) :- append(T1, X, T2).
      

      see how to split a list image

  6. findall(result, target, result_list): find all elements in target mode and store them in result_list in result mode

    fruit(apple).
    fruit(banana).
    

    image

12. Operator

  1. math operator image

  2. operator

    1. infix: 3 + 10
    2. prefix: -13
    3. postfix: 8 factorial
  3. operator precedence

    1. precedence value: 1 ~ 1200
    2. value smaller, priority bigger
    3. op(value, fix, name_of_operator)image
    fix name trait
    Infix xfx non-associative
    Infix xfy right to left
    Infix yfx left to right
    Prefix fx non-associative
    Prefix fy left to right
    Postfix xf non-associative
    Postfix yf right to left
  4. : operator

    obj(apple, size: small, color: red).
    

    image

13. Cut

  1. cut!: add ! in the rule will cut the search

    fruit(apple).
    fruit(banana).
    fruit(orange).
    
    cut_test1(X) :- fruit(X).
    cut_test1('last clause').
    
    cut_test2(X):- fruit(X), ! .
    cut_test2('last clause').
    

    image

  2. ! suppresses the traceback of the left target, while the target to its right is unaffected

    cut_test3(X, Y) :- fruit(X), ! , fruit(Y).
    

    image

  3. not(X): negate X bool value

  4. not basic principle

    not(X) :- call(X), !, fail.
    not(X).
    

14. Process Control

  1. repeat: always succeed, provide an infinite number of choice points

  2. how to create a endless loop:

    command_loop :- repeat, fail.
    
  3. loop: read in a simple command and echoed on the screen until the user enters end

    command_loop :-
        repeat,
        write('Enter command (end to exit): '), 
        read(X), 
        write(X), nl, 
        X = end.
    

    image

  4. Tail Recursion

    1. Tail Resursion: using recursion to repeat; its form is a recursive statement at the end of the function, and the computation of each layer does not need to use the return information of the next layer so that a good Prolog interpreter does not need to rely on a stack
    2. e.g. factorial(number, 1, answer) -> answer := number!
      factorial(1, F, F).
      factorial(N, T, F) :- 
          N > 1, 
          NEXT_T is N * T,
          NEXT_N is N - 1, 
          factorial(NEXT_N, NEXT_T, F).
      
      5! = 120;
      image

15. Natural Language

  1. And Proof: first find out all the possible breakdown of a sentence, then test whether each part of breakdown is legal

  2. Diff Table: including two tables: full table and remainder table, which can be used as two arguments of the predicate; we use - to connect two tables to make it easier to read, in the form of X - Y

    • e.g.
      sentence(S) :-
          nounphrase(S - S1),
          verbphrase(S1 - []).
      
      noun([dog|X] - X).
      noun([cat|X] - X).
      noun([mouse|X] - X).
      verb([ate|X] - X).
      verb([chase|X] - X).
      
      adjective([big|X] - X).
      adjective([brown|X] - X).
      adjective([lazy|X] - X).
      
      determiner([the|X] - X).
      determiner([a|X] - X).
      
      nounphrase(NP - X):-
          determiner(NP - S1),
          nounexpression(S1 - X).
      
      nounphrase(NP - X):-
          nounexpression(NP - X).
      
      nounexpression(NE - X):-
          noun(NE - X).
      
      nounexpression(NE - X):-
          adjective(NE - S1),
          nounexpression(S1 - X).   % recursively deal with any number of adj.
      
      verbphrase(VP - X):-
          verb(VP - S1),
          nounphrase(S1 - X).
      
      image
  3. Definite Clause Grammar -- DCG

    1. DCG: Diff tables are often used in Prolog, so many Prolog versions have good support for diff tables. This syntax is called DCG, and it looks very similar to a normal Prolog clause, except that :- is replaced by -->, which is translated by Prolog into the normal difference table
    2. pred --> arg = pred([arg|X], X)
    3. using DCG, the first part of the last instance can be:
      sentence --> nounphrase, verbphrase.
      
      % noun([dog|X] - X).
      noun --> [dog].
      
  4. =..: change a predicate to a list
    image

标签:apple,T2,list,Syntax,fruit,location,Basic,kitchen,Prolog
From: https://www.cnblogs.com/RadiumGalaxy/p/17231404.html

相关文章

  • java.sql.SQLSyntaxErrorException: Table 'test.user' doesn't exist报错问题解决
    以下内容仅供自己学习使用,侵权必删在使用mubatis-plus的时候报错了以下内容java.sql.SQLSyntaxErrorException:Table'test.user'doesn'texist解决方法:2.1在......
  • MySQL8设置用户权限报错You have an error in your SQL syntax;right syntax to use ne
    mysql8设置用户权限命令和之前不一样之前:grantallprivilegeson*.*to'myuser'@'%'identifiedby'mypassword'withgrantoption;报错:Youhaveanerrorinyou......
  • PAT Basic 1033. 旧键盘打字
    PATBasic1033.旧键盘打字1.题目描述:旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现。现在给出应该输入的一段文字、以及坏掉的那些键,打出的结果文字......
  • PAT Basic 1031. 查验身份证
    PATBasic1031.查验身份证1.题目描述:一个合法的身份证号码由17位地区、日期编号和顺序编号加1位校验码组成。校验码的计算规则如下:首先对前17位数字加权求和,权重分配......
  • PAT Basic 1030. 完美数列
    PATBasic1030.完美数列1.题目描述:给定一个正整数数列,和正整数\(p\),设这个数列中的最大值是\(M\),最小值是\(m\),如果\(M≤mp\),则称这个数列是完美数列。现在给定......
  • PAT Basic 1029. 旧键盘
    PATBasic1029.旧键盘1.题目描述:旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现。现在给出应该输入的一段文字、以及实际被输入的文字,请你列出肯定坏......
  • Pycharm报错 : SyntaxError: Non-ASCII character ' but no encoding declared;
     File"D:/03��ѧ/2023�괺��Python/0310/����ѧ�ź������Ƚ�v3--��Ѷ���鿼��ר��--12��.py",line1SyntaxError:Non-ASCIIcharacter'\xe6'infileD:/03��ѧ/2023�괺��Python/0310/����ѧ�ź������Ƚ�v3--��Ѷ���鿼��ר......
  • 项目构建node-sass源码报错 SyntaxError:Unexpectedtoken"?"
    背景vue2项目,之前一直构建正常。今天改了代码,构建时报错,报错原因显示编译node-sass源码时出错。报错信息:Modulebuildfailed:/node_modules/node-sass/sass.dart.js:19......
  • PAT Basic 1028. 人口普查
    PATBasic1028.人口普查1.题目描述:某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。这里确保每个输入的日期都是合法的,但不一......
  • PAT Basic 1025. 反转链表
    PATBasic1025.反转链表1.题目描述:给定一个常数 \(K\) 以及一个单链表 \(L\),请编写程序将 \(L\) 中每 \(K\) 个结点反转。例如:给定 \(L\) 为\(1→2→3→4→......