Prolog e lógica

22
Prolog e lógica Prolog e lógica Jacques Robin, DI-UFPE www.di.ufpe.br/~jr

description

Prolog e lógica. Jacques Robin, DI-UFPE www.di.ufpe.br/~jr. Cláusulas de Horn. Formulas de L1: em forma normal implicativa com uma conclusão única e positiva ie, da forma: Muitas mas nem todas as formulas de L1 tem conjunto equivalente de cláusulas de Horn, cex : Lógica de Horn:. - PowerPoint PPT Presentation

Transcript of Prolog e lógica

Page 1: Prolog e lógica

Prolog e lógicaProlog e lógica

Jacques Robin, DI-UFPEwww.di.ufpe.br/~jr

Page 2: Prolog e lógica

Cláusulas de HornCláusulas de Horn

Formulas de L1:• em forma normal implicativa• com uma conclusão única e positiva• ie, da forma:

Muitas mas nem todas as formulas de L1 tem conjunto equivalente de cláusulas de Horn, cex:

Lógica de Horn: nnH hhfHorndeclaúsulashhLfL 1111 ,,/

CPP n 1

FYXkillsYanimalXranimalLoveYX ),()()(,

Page 3: Prolog e lógica

Cláusulas Prolog e cláusulas de HornCláusulas Prolog e cláusulas de Horn

Fatos Prolog:• cláusulas de Horn com premissa única T implícita• ex: C. <=> T => C

Regras Prolog:• outras cláusulas de Horn • ex: C :- P1, ... ,Pn. <=> P1 & ... & Pn => C

Premissas de cláusulas com a mesma conclusão são implicitamente disjuntivas:• ex: {C :- P1, ... ,Pn., C :- Q1, ... ,Qm} <=> (P1& ... & Pn) v (Q1 & ... & Qm) => C

Escopo das variáveis = uma cláusula

Page 4: Prolog e lógica

West é criminoso?West é criminoso? : em L1 : em L1

Requisitos em inglês1. It is crimimal for an

American to sell weapons to an hostile country

2. Nono owns missiles3. Nono acquires all its missiles

from West4. West is American5. Nono is a nation6. Nono is an enemy of the

USA0. Is West a crimimal?

Em L11. V P,W,N american(P) & weapon(W)

& nation(N) & hostile(N) & sells(P,N,W) => criminal(P)

2. E W owns(nono,W) & missile(W)3. V W owns(nono,W) & missile(W)

=> sells(west,nono,W)7. V X missile(W) => weapon(W)8. V X enemy(N,america) =>

hostile(N)4. american(west)5. nation(nono)6. enemy(nono,america)9. nation(america)

Page 5: Prolog e lógica

West é criminoso?West é criminoso? em formal normalem formal normal

Em L1:V P,W,N american(P) & weapon(W)

& nation(N) & hostile(N) & sells(P,N,W) => criminal(P)

E W owns(nono,W) & missile(W)V W owns(nono,W) & missile(W)

=> sells(west,nono,W)V X missile(W) => weapon(W)V X enemy(N,america) =>

hostile(N)american(west)nation(nono)enemy(nono,america)nation(america)

Em formal normalamerican(P) & weapon(W) &

nation(N) & hostile(N) & sells(P,N,W) => criminal(P)

owns(nono,m1)missile(m1)owns(nono,W) & missile(W) =>

sells(west,nono,W)missile(W) => weapon(W)enemy(N,america) => hostile(N)american(west)nation(nono)enemy(nono,america)nation(america)

Page 6: Prolog e lógica

West é criminoso?West é criminoso? em Prolog em Prolog

Em lógica de Horn:american(P) & weapon(W) &

nation(N) & hostile(N) & sells(P,N,W) => criminal(P)

owns(nono,m1)missile(m1)owns(nono,W) & missile(W) =>

sells(west,nono,W)missile(W) => weapon(W)enemy(N,america) => hostile(N)american(west)nation(nono)enemy(nono,america)nation(america)

Em Prolog:criminal(P) :- american(P),

weapon(W), nation(N), hostile(N), sells(P,N,W).

owns(nono,m1).missile(m1).sells(west,nono,W) :-

owns(nono,W), missile(W).weapon(W) :- missile(W).hostile(N) :- enemy(N,america).american(west).nation(nono).enemy(nono,america).nation(america).

Page 7: Prolog e lógica

Interpretador Prolog: controle e Interpretador Prolog: controle e buscabusca

Aplica regra de resolução:• com estratégia linear (sempre tenta unificar ultimo

fato a provar com a conclusão de uma cláusula do programa),

• na ordem de escritura das cláusulas no programa, • com encadeamento de regras para trás, • busca em profundidade e• da esquerda para direita das premissas das cláusulas,• e com backtracking sistemático e linear quando a

unificação falha,• e sem occur-check na unificação.

Estratégia eficiente mas incompleta.

Page 8: Prolog e lógica

Verificação de ocorrênciaVerificação de ocorrência

Ao contrario da unificação da resolução: • unificação de Prolog é sem occur-check,• quando chamado com uma variável X e um literal l, • instância X com l, sem verificar antes se X ocorre em l.

Junto com a busca em profundidade:• faz que Prolog pode entrar em loop com regras

recursivas, • ex: c(X) :- c(p(X)). gera lista infinita de objetivos:• c(p(U)), c(p(p(U))), c(p(p(p(U)))), ...• cabe ao programador de não escrever tais regras,• torna a unificação linear no lugar de quadrática• no tamanho dos termos a unificar

Page 9: Prolog e lógica

West é criminoso?West é criminoso? busca busca

criminal(P) :- american(P), weapon(W), nation(N), hostile(N), sells(P,N,W).

owns(nono,m1).missile(m1).sells(west,nono,W) :-

owns(nono,W), missile(W).weapon(W) :- missile(W).hostile(N) :- enemy(N,america).american(west).nation(nono).enemy(nono,america).nation(america).

criminal(west)? <- yes.•american(west)? -> yes.•weapon(W)? <- W = m1.

missile(W)? -> W = m1.•nation(N)? -> N = nono.•hostile(nono)? <- yes.

enemy(nono,america)? -> yes.

•sells(west,nono,m1)? <- yes.owns(nono,m1)? -> yes.missile(m1)? -> yes.

Page 10: Prolog e lógica

West é criminoso?West é criminoso? backtracking backtracking

criminal(P) :- american(P), weapon(W), nation(N), hostile(N), sells(P,N,W).

owns(nono,m1).missile(m1).sells(west,nono,W) :-

owns(nono,W), missile(W).weapon(W) :- missile(W).hostile(N) :- enemy(N,america).american(west).nation(america).enemy(nono,america).nation(nono).

criminal(west)? <- yes.•american(west)? -> yes.•weapon(W)? <- W = m1.

missile(W)? -> W = m1.•nation(N)? -> N = america.•hostile(america)? <- no.

enemy(america,america)? -> no.

•backtrack: nation(N), N \ {america}? -> N = nono.•hostile(nono)? <- yes.

enemy(nono,america)? -> yes.•sells(west,nono,m1)? <- yes.

owns(nono,m1)? -> yes.missile(nono,m1)? -> yes.

Page 11: Prolog e lógica

Prolog devolve a primeira respostaProlog devolve a primeira resposta

g1(a).g21(a).g3(a).g4(a).g1(b).g21(b).g22(b).g3(b).g(X) :- g1(X), g2(X).g(X) :- g3(X), g4(X).g2(X) :- g21(X), g22(X).

$ prolog?- consult(“g.pl”).yes?- g(U).U = b?- ;U = a ?- ;no?- halt.$

Page 12: Prolog e lógica

Forçar o backtracking para obter Forçar o backtracking para obter todas as respostastodas as respostas

g1(a).g21(a).g3(a).g4(a).g1(b).g21(b).g22(b).g3(b).g(X) :- g1(X), g2(X).g(X) :- g3(X), g4(X).g2(X) :- g21(X), g22(X).

g(U)? <- U = b. g1(U)? -> U = a. g2(a)? <- no.

• g21(a)? -> yes.• g22(a)? -> no.

g1(U), U \ {a}? -> U = b. g2(b)? <- yes.

• g21(b)? -> yes.• g22(b)? -> yes.

; g1(U), U \ {a,b} ? -> no.

Page 13: Prolog e lógica

Backtracking em cascatasBacktracking em cascatas

g1(a).g21(a).g3(a).g4(a).g1(b).g21(b).g22(b).g3(b).g(X) :- g1(X), g2(X).g(X) :- g3(X), g4(X).g2(X) :- g21(X), g22(X).

g(U), g \ {g1,g2}? <- U = a. g3(U)? -> U = a. g4(a)? -> yes.; g3(U), U \ {a}? -> U = b. g4(b)? -> no. g3(U), U \ {a,b}? -> no.g(U), g \ {g1,g2 ; g3,g4}? -

> no.

Page 14: Prolog e lógica

Prolog: sintaxe 1 Prolog: sintaxe 1

fato -> fa. (abrev. para Formula Atômica) regra -> fa0 :- fa1, ... , faN. consulta -> fa1, ... , faN. fa -> pred(termo1, ... , termoN) | preop termo1 termo2 | termo1 inop termo2 | termo1 termo2 postop termo -> constante | variável | fa constante -> átomos | numeros pred -> átomo Ao invés de L1:

• nenhuma distinção entre predicados e funções• ausência da igualdade semântica

Page 15: Prolog e lógica

Prolog: sintaxe 2Prolog: sintaxe 2

variável ex: G, Glr, geber-ramalho, 1geber, _glr, _ átomo ex: g, glr, =>, geber_ramalho, geber1, ‘geber ramalho’ número ex: 23 termos, fatos, regras e consultas sem variáveis:

• instanciados (ground)• ex.: person(bob,40,cs).

termos, fatos e regras com variáveis: • universais• ex.: pai(X,adao). ancestral(X,A) :- pai(X,P), ancestral(P,A).

consultas com variáveis: • existenciais• ex.: ? pai(F,P).

Page 16: Prolog e lógica

Prolog: semânticaProlog: semântica

Programa Prolog P possui 2 semânticas:• semântica declarativa

semântica das formulas de Lp correspondendo as cláusulas de P

3 abordagens:¤ conjunto mínimo de termos instanciados verificando P

(base de Herbrand, model-theoretic) ¤ procedimento de verificação de uma consulta (resolução,

proof-theoretic)¤ operador de ponto fixo gerando todas as a formulas

atômicas conseqüências lógicas de P

• semântica procedimental execução de P pelo interpretador Prolog

Page 17: Prolog e lógica

Estudo de caso: Estudo de caso: a terrível novelaa terrível novelarequisitos em Inglêsrequisitos em Inglês

1. A soap opera is a TV show whose characters include a husband, a wife and a mailman such that:

2. the wife and the mailman blackmail each other 3. everybody is either alcoholic, drug addict or gay 4. Dick is gay, Jane is alcoholic and Harry is a drug addict 5. the wife is always an alcoholic and the long-lost sister of her

husband 6. the husband is always called Dick and the lover of the mailman 7. the long-lost sister of any gay is called either Jane or Cleopatra 8. Harry is the lover of every gay 9. Jane blackmails every drug addicted lover of Dick 10. soap operas are invariably terrible! 0. Who are the characters of a terrible TV show?

Page 18: Prolog e lógica

Exercício 1:Exercício 1:A terrível novelaA terrível novela em L1 em L1

Page 19: Prolog e lógica

Exercício 2:Exercício 2:A terrível novelaA terrível novela em Prolog em Prolog

Page 20: Prolog e lógica

Estudo de caso: Estudo de caso: o banco de dados acadêmicoo banco de dados acadêmico

requisitos em Inglêsrequisitos em Inglês

1. Bob is 40 and is the manager of the CS department. 2. His assistants are John and Sally. 3. Mary’s highest degree is an MS. 4. She works at the CS department and is friend to Bob and Sally.

5. Every faculty is a midaged person who writes article, makes in the average $50,000 a year and owns a degree of some kind, typically a PhD.

6. A faculty’s boss is both a faculty and a manager. 7. Every person has a name, friends who must be persons, and children who also

must be persons. 8. Every employee is affiliated to some department, has a boss who is also an

employee and joint work on reports with other employees. 9. Every department has a manager who is an employee and assistants who are

both employees and students 10. A boss is an employee who is the manager of another employee of the same

department. 11. A joint work is a paper that is written by two faculties 0a: Who are the midaged employees of the CS department and who are their

boss? 0b: Who published jointly with Mary in the Journal of the ACM? 0c: Where did Mary published joint work with Phil?

Page 21: Prolog e lógica

Exercício 3:Exercício 3:O banco de dados acadêmicoO banco de dados acadêmico

em Prologem Prolog

Page 22: Prolog e lógica

Exercício 4:Exercício 4:O banco de dados acadêmico O banco de dados acadêmico em L1em L1