prolog e lógica
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 PresentationTRANSCRIPT
Prolog e lógicaProlog e lógica
Jacques Robin, DI-UFPEwww.di.ufpe.br/~jr
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 ),()()(,
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
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)
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)
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).
Interpretador Prolog: controle e buscaInterpretador Prolog: controle e busca
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.
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
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.
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.
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.$
Forçar o backtracking para obter todas Forçar o backtracking para obter todas as respostasas 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.
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.
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
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).
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
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?
Exercício 1:Exercício 1:A terrível novelaA terrível novela em L1 em L1
Exercício 2:Exercício 2:A terrível novelaA terrível novela em Prolog em Prolog
Estudo de caso: Estudo de caso: o BD acadêmicoo BD acadêmicoRequisitos em InglêsRequisitos em Inglês
1. Bob is 40 and the manager of the CS department.
2. His assistants are John and Sally. 3. Mary’s highest degree is an MS and she
works at the CS department. 4. She co-authored with her boss and her
friends, John and Sally, a paper published in the Journal of the ACM.
5. Phil is a faculty, who published a paper on F-Logic at a Conference of the ACM, jointly with Mary and Bob.
6. 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.
7. One is considered midage if one is between 30 and 50 years old.
8. A faculty’s boss is both a faculty and a manager.
9. Friends and children of a person are also persons.
10. Every department has a manager who is an employee and assistants who are both employees and students
11. A boss is an employee who is the manager of another employee of the same department.
12. A joint work is a paper that is written by two faculties
13. There are three types of papers: technical reports, journal papers and conference papers
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?
Exercício 3:Exercício 3:O banco de dados acadêmicoO banco de dados acadêmico
em Prologem Prolog
Exercício 4:Exercício 4:O banco de dados acadêmico O banco de dados acadêmico em L1em L1
Coloração de mapaColoração de mapa
Colorir mapa tal que:• países adjacentes• de cores diferentes
A B
C
F
D
E
Instância de problema de resolução de restrições
A B
C
F
D
E