Skip to content

Instantly share code, notes, and snippets.

@HiroNakamura
Last active April 27, 2024 19:39
Show Gist options
  • Save HiroNakamura/bb1c0d793cd121baecb64f1e7a8d5086 to your computer and use it in GitHub Desktop.
Save HiroNakamura/bb1c0d793cd121baecb64f1e7a8d5086 to your computer and use it in GitHub Desktop.
Aprendiendo Prolog

Prolog

Aprendiendo Prolog

Prolog (PROLOG), proveniente del francés PROgrammation en LOGique,1​ es un lenguaje de programación lógico e interpretado usado habitualmente en el campo de la Inteligencia artificial.

Prolog es un lenguaje de programación declarativo que se utiliza para resolver problemas en los que existen objetos y las relaciones entre ellos.

Los lenguajes declarativos se diferencian de los lenguajes imperativos en que están basados en formalismos abstractos (Prolog tiene sus fundamentos en la lógica de predicados o de primer orden), por lo tanto su semántica no depende de la máquina en la que se ejecutan.

Busca obtener conocimiento declarando hechos sobre los objetos y sus relaciones, creando reglas sobre dichos objetos y relaciones y realizando preguntas en ese dominio. Está basado en los siguientes mecanismos básicos: unificación, estructuras de datos basadas en árboles y backtracking.

Los programas en Prolog son programas lógicos definidos, este se basa en un conocimiento base para solucionar consultas así como inferir información y el conocimiento lo representamos mediante cláusulas de Horn positivas. Las cláusulas son hechos o reglas , están compuestas usualmente de predicados.

La mayoría de los programas Prolog están organizados en cuatro secciones principales:

Dominio: donde se declaran los argumentos que utilizarán los predicados.
Predicados: donde se declaran todos los predicados no predefinidos que se utilizarán en las siguientes secciones.
Objetivos: esta sección permite ejecutar los programas de forma no interactiva, y por tanto, buscará la solución deseada tan pronto como se ejecute el programa. Como también es habitual usar Prolog de forma interactiva es frecuente ejecutar un programa y luego esperar a que se nos pregunte por los objetivos.
Clausulas: donde se escriben los hechos y las reglas que conocemos del dominio.

Instalación

sudo add-apt-repository ppa:swi-prolog/stable
sudo apt-get update
sudo apt-get install swi-prolog -y
swipl -s programa.pl

Entrar al Shell

$ swipl

?- True.
% ... 1,000,000 ............ 10,000,000 years later
% 
%       >> 42 << (last release gives the question)
?- False.
% ... 1,000,000 ............ 10,000,000 years later
% 
%       >> 42 << (last release gives the question)
?- 
?- 5 is 3+2
true
? 6 is 3*3
false
?- [saber].
true.

?- sabe(luis,X,Y).
X = ingles,
Y = 5 ;
X = chino,
Y = 2.

?- sabe(marta,X,Y).
X = ruso,
Y = 3 ;
X = chino,
Y = 5.

?- sabe(luis,chino,X).
X = 2.

?- sabe(marta,chino,X).
X = 5.

?- sabe(luis,frances,X).
false.

?- sabe(marta,aleman,Y).
false.

?- halt. % terminar sesión

Crear ejecutable

# Crear ejecutable de Proglog
swipl -o nombre_de_ejecutable -g funcion_principal -c programa.pl

Enlaces

#!/usr/bin/swipl -q -t animals -f
animal(dog) :- is_true("Tiene pelo"), is_true("Dice guau").
animal(cat) :- is_true("Tiene pelo"), is_true("Dice miau").
animal(duck) :- is_true("tiene plumas"), is_true("Dice cuauc").
is_true(Q) :-
format("~s?\n", [Q]),
read(yes).
#!/usr/bin/swipl -q -t basicas -f
suma(A+B,X):- X is A+B.
resta(A-B,X):- X is A-B.
multi(A*B,X):- X is A*B.
divi(A/B,X):- X is A/B.
#!/usr/bin/swipl -q -t bigger -f
bigger(elefante, tigre).
bigger(tigre, conejo).
bigger(conejo, raton).
bigger(raton, hormiga).
#!/usr/bin/swipl -q -t comidas -f
comidas(ramen,mango).
comidas(ramen,durazno).
comidas(hordal,lechuga).
comidas(hordal,tomate).
comidas(hordal,pepino).
#!/usr/bin/swipl -q -t direccion -f
jefe(mateo).
jefe_subdir(mateo,federico).
jefe_subdir(mateo,berenice).
jefe_subdir(mateo,julio).
subdir_emp(federico,tomas).
subdir_emp(federico,maria).
subdir_emp(berenice,olga).
subdir_emp(berenice,omar).
subdir_emp(julio,hector).
subdir_emp(julio,irene).
#!/usr/bin/swipl -q -t division -f
% Regla
dividir(Numero, Divisor, Division) :-
Divisor \= 0,
Division is Numero / Divisor.
#!/usr/bin/swipl -q -t even_and_odd -f
% Par
even(X) :- 0 is mod(X, 2).
% Impar
odd(X) :- 1 is mod(X, 2).
#!/usr/bin/swipl -q -t fibonnaci -f
fibonnaci(0, 1) :- !.
fibonnaci(1, 1) :- !.
fibonnaci(N, F) :-
N > 1,
N1 is N-1,
N2 is N-2,
fibonnaci(N1, F1),
fibonnaci(N2, F2),
F is F1+F2.
#!/usr/bin/swipl -q -t heroes -f
% Hechos
heroe(spiderman,peter).
heroe(superman,clark).
heroe(batman,bruce).
heroe(hulk,banner).
heroe(daredevil,murdock).
heroe(robocop,murphy).
heroe(ironman,stark).
heroe(dredd,unknown).
% Preguntas
es_super_heroe(Super,Nombre):- heroe(Super,Nombre).
super_heroe(heroe):- es_verdad("Tiene traje"),es_verdad("Ayuda a la gente").
super_heroe(villano):- es_verdad("Tiene traje"),es_verdad("No ayuda a la gente").
es_verdad(Q):-format('~s?\n', [Q]),read(yes).
#!/usr/bin/swipl -q -t holamundo -f
holamundo :- write('Hola, mundo en Prolog!!'), nl, halt.
#!/usr/bin/swipl -q -t mayora100 -f
es_mayor_a_100(X):- X > 100.
% user shell
go :-
write('****************** My Expert System for Medical Diagnosis*********************** '),nl,write('System menu'),nl,
hypothesis(Patient,Organism).
go :-
write('It can be said with 0.3 CF(Certainty Factor) that the bacteroides '),nl,
write('have not entered the patient'),nl.
%knowledge base
hypothesis(Patient,majorbacteroides) :-
symptom(Patient,majorinfection),
symptom(Patient,bacterial),
symptom(Patient,site),
symptom(Patient,portal),
write_list(['Patient probably has 0.7 CF(Certainty Factor) chance of majorbacteroides.']),
nl,
write('Medical Diagnosis:Patient is adviced to take Penicilin , Cephalophorins and Chloramphenicol'),nl.
hypothesis(Patient,minorbacteroides) :-
symptom(Patient,minorinfection),
symptom(Patient,bacterial),
write_list(['Patient probably has 0.7 CF(Certainty Factor) chance of minorbacteroides.']),
nl,write('Medical Diagnosis:Patient is adviced to urgently go to doctor for diagnosis'),nl.
%inference engine
symptom(Patient,majorinfection) :-
write_list(['Does Patient have a major infection (y/n) ?']),
response(Reply),
Reply='y'.
symptom(Patient,minorinfection) :-
write_list(['Does Patient have a minor infection (y/n) ?']),
response(Reply),
Reply='y'.
symptom(Patient,bacterial) :-
write_list(['Does Patient have a bacterial infection (y/n) ?']),
response(Reply),
Reply='y'.
symptom(Patient,site) :-
write_list(['Does Patient have the site of culture as sterilesite (y/n) ?']),
response(Reply),
Reply='y'.
symptom(Patient,portal) :-
write_list(['Does Patient have a portal of entry as gastrointestinal tract (y/n) ?']),
response(Reply),
Reply='y'.
write_list([]).
write_list([Term| Terms]) :-
write(Term),
write_list(Terms).
response(Reply) :-
get_single_char(Code),
put_code(Code), nl,
char_code(Reply, Code).
% Tiene errores por corregir
% Console Shell
go :-
write(' ==== [ MENU DEL PROGRAMA ] ==== '),nl,
write(' 1. Saludar '),nl,
write(' 2. Salir '),nl,
write('Escribe una opcion: '),nl,
read(X),
choice(X).
choice(X):-
X=:=1,
write('Bienvenido al mundo Prolog.'),
menu.
choice(X):-
X=:=2,
consult('Has salido del programa.'),halt.
#!/usr/bin/swipl -q -t mimenu -f
% Reglas
bienvenida:-
write('Bienvenidos.'),
nl.
salir:-
write('Adios'),
nl,
halt.
menu:-
write(' *** Menu *** '),nl,
write(' 1. Bienvenida '),nl,
write(' 2. Salir '),nl,
read(
Opcion=:=1->
bienvenida,
menu;
Opcion=:=2->
salir
).
% Visto en: https://gist.github.com/thechaudharysab/aa2e57d4dcb37d113f675cf9c47fb94e#file-music-suggestion-pl
% is used to add comments in code in prolog language
suggest(S) :- write('What is your personality type?: '),read(P),write('How is your mood?: '),read(M), song(S,_,M,P).
%Happy_Mood
song('https://www.youtube.com/watch?v=c8YIlU_30Kk',jazz,M,P):- M = happy ,(P= (entj) ; P=(enfj) ; P=(enfp)),!.
song('https://www.youtube.com/watch?v=SsZRci3sA4I',classical,M,P):- M = happy ,(P= (entj) ; P=(intj) ; P=(entp) ; P=(infj)),!.
song('https://www.youtube.com/watch?v=XYk2kt8K6E0',electronica,M,P):- M = happy ,(P= (entj) ; P=(estp) ; P=(enfp)),!.
song('https://www.youtube.com/watch?v=VguED7BfpgU',metal,M,P):- M = happy ,(P= (intj) ; P=(istp) ; P=(intp) ; P=(estp)),!.
song('https://www.youtube.com/watch?v=5f-wQBh-zbQ',alternative_rock,M,P):- M = happy ,(P= (intj) ; P=(entp) ; P=(infj) ; P=(infp) ; P=(istj) ; P=(isfj) ; P=(istp)),!.
song('https://www.youtube.com/watch?v=lPIiB02uqXM',rock,M,P):- M = happy ,(P= (entp) ; P=(intp) ; P=(infp) ; P=(istj) ; P=(isfj)),!.
song('https://www.youtube.com/watch?v=PIfJ7nYQFTM',punk,M,P):- M = happy ,(P= (intp) ; P=(infp) ; P=(istp)),!.
song('https://www.youtube.com/watch?v=eWyeAIlaYUY',world,M,P):- M = happy ,(P= (infj) ; P=(enfj)),!.
song('https://www.youtube.com/watch?v=qAqKsw4GjB0',blues,M,P):- M = happy ,(P= (enfj)),!.
song('https://www.youtube.com/watch?v=w47D1Fqn_sA',ambient,M,P):- M = happy ,(P= (enfp) ; P=(isfp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=HA06Rr3bRVc',pop_songs,M,P):- M = happy ,(P= (istj) ; P=(estj) ; P=(isfp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=qCZAynQU_-8',religious,M,P):- M = happy ,(P= (isfj) ; P=(estj)),!.
song('https://www.youtube.com/watch?v=hvVPMIqRulE',hip_hop,M,P):- M = happy ,(P= (estj) ; P=(estp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=X7ses5rI5U4',soul,M,P):- M = happy ,(P= (esfj)),!.
song('https://www.youtube.com/watch?v=NKzyyxvNiFc',country,M,P):- M = happy ,(P= (esfj)),!.
song('https://www.youtube.com/watch?v=oWQpQW95Ru8',reggae,M,P):- M = happy ,(P= (isfp)),!.
%Sad_Mood
song('https://www.youtube.com/watch?v=McxPJ3RYY4Y',jazz,M,P):- M = sad ,(P= (entj) ; P=(enfj) ; P=(enfp)),!.
song('https://www.youtube.com/watch?v=R6OElQVVlLo',classical,M,P):- M = sad ,(P= (entj) ; P=(intj) ; P=(entp) ; P=(infj)),!.
song('https://www.youtube.com/watch?v=ilTbMVG5t6M',electronica,M,P):- M = sad ,(P= (entj) ; P=(estp) ; P=(enfp)),!.
song('https://www.youtube.com/watch?v=SWkKvDD-Gu4',metal,M,P):- M = sad ,(P= (intj) ; P=(istp) ; P=(intp) ; P=(estp)),!.
song('https://www.youtube.com/watch?v=-fvBrKeobyA',alternative_rock,M,P):- M = sad ,(P= (intj) ; P=(entp) ; P=(infj) ; P=(infp) ; P=(istj) ; P=(isfj) ; P=(istp)),!.
song('https://www.youtube.com/watch?v=qGxO2YNFj1o',rock,M,P):- M = sad ,(P= (entp) ; P=(intp) ; P=(infp) ; P=(istj) ; P=(isfj)),!.
song('https://www.youtube.com/watch?v=2MRdtXWcgIw',punk,M,P):- M = sad ,(P= (intp) ; P=(infp) ; P=(istp)),!.
song('https://www.youtube.com/watch?v=F90ymkS2dt4',world,M,P):- M = sad ,(P= (infj) ; P=(enfj)),!.
song('https://www.youtube.com/watch?v=6R9nWRWgl90',blues,M,P):- M = sad ,(P= (enfj)),!.
song('https://www.youtube.com/watch?v=sbX_aElB2dI',ambient,M,P):- M = sad ,(P= (enfp) ; P=(isfp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=T8-96tqFCFU&vl=en',pop_songs,M,P):- M = sad ,(P= (istj) ; P=(estj) ; P=(isfp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=K_-e99oLp4Y',religious,M,P):- M = sad ,(P= (isfj) ; P=(estj)),!.
song('https://www.youtube.com/watch?v=0pZmHnj3-jQ',hip_hop,M,P):- M = sad ,(P= (estj) ; P=(estp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=KVIwQFEyZQE',soul,M,P):- M = sad ,(P= (esfj)),!.
song('https://www.youtube.com/watch?v=ygxmpkHgaC8',country,M,P):- M = sad ,(P= (esfj)),!.
song('https://www.youtube.com/watch?v=FqQjAUB6DJY',reggae,M,P):- M = sad ,(P= (isfp)),!.
%! is called cut and is used to reduce backtracking
#!/usr/bin/swipl -q -t padres -f
% Hechos
padre(maria,pedro).
padre(juan,pedro).
padre(juan,carola).
padre(pedro,ana).
padre(pedro,paty).
padre(paty,aldo).
#!/usr/bin/swipl -q -t permisos -f
% Hehos
permiso(jimena,facebook).
permiso(jimena,google).
permiso(ursula,google).
permiso(ursula,youtube).
%Reglas
tiene_permiso(Usuario,Sitio):- permiso(Usuario,Sitio).
% Hechos
programador(fernando).
programador(mariana).
programador(paco).
programador(ernesto).
% Hechos y relaciones
que_usa(fernando,java).
que_usa(mariana,javascript).
que_usa(paco,python).
que_usa(ernesto,prolog).
% Reglas
quien_programa(X,Y):- programador(X),que_usa(X,Y).
quien_es_back(X):- que_usa(X,java); que_usa(X,python).
quien_es_front(X):- que_usa(X,javascript).
quien_es_(X,Y):- que_usa(X,Y).
% Hechos
programador(fernando).
programador(mariana).
programador(paco).
programador(ernesto).
% Hechos y relaciones
que_usa(fernando,java).
que_usa(fernando,javascript).
que_usa(mariana,javascript).
que_usa(mariana,jquery).
que_usa(paco,python).
que_usa(paco,php).
que_usa(ernesto,prolog).
que_usa(ernesto,html5).
esBackend(fernando,si).
esBackend(mariana,no).
esBackend(paco,si).
esBackend(ernesto,no).
esFrontend(fernando,si).
esFrontend(mariana,si).
esFrontend(paco,si).
esFrontend(ernesto,si).
esFullstak(fernando,si).
esFullstack(paco,si).
esFullstack(mariana,no).
esFullstack(ernesto,no).
% Reglas
quien_programa(X,Y):- programador(X),que_usa(X,Y).
quien_es_back(X):- que_usa(X,java); que_usa(X,python).
quien_es_front(X):- que_usa(X,javascript).
quien_es_(X,Y):- que_usa(X,Y).
% Preguntas
escribeProgramas(Sujeto):-programador(Sujeto).
% IF escribeProgramas AND (esBackend OR esFullstack) THEN
programaAPIS(Sujeto):- escribeProgramas(Sujeto),esBackend(Sujeto,si);esFullstack(Sujeto,si).
% IF escribeProgramas AND (esFrontend OR es Fullstack) THEN
programaWebs(Sujeto):- escribeProgramas(Sujeto),esFrontend(Sujeto,si);esFullstack(Sujeto,si).
#!/usr/bin/swipl -q -t programadores -f
% Hechos
programador(leticia).
programador(jose).
programador(ana).
% Preguntas
escribeProgramas(Sujeto):- programador(Sujeto).
% Hechos y relaciones
esBackend(leticia,si).
esBackend(ana,si).
esBackend(jose,no).
esFrontend(leticia,si).
esFrontend(ana,no).
esFrontend(jose,si).
esFullstack(leticia,si).
esFullstack(ana,no).
esFullstack(jose,no).
% Reglas
programadorAPIS(Sujeto):- escribeProgramas(Sujeto), esBackend(Sujeto,si);esFullstack(Sujeto,si).
% Uso
% [programadores]
% > programadorAPIS(jose).
#!/usr/bin/swipl -q -t relaciones -f
% Hechos
relacion(a,c).
relacion(b,c).
relacion(d,d).
relacion(c,e).
relacion(c,f).
relacion(f,g).
% Preguntas:
% relacion(a,X),relacion(X,Y).
% relacion(a,X),relacion(X,Y), relacion(Y,g).
#!/usr/bin/swipl -q -t saber -f
% Hechos
sabe(luis,ingles,5).
sabe(luis,chino,2).
sabe(marta,ruso,3).
sabe(marta,chino,5).
% Hechos
subordinados(monica,grabriela).
subordinados(gabriela,ana).
subordinados(gabriela,jose).
subordinados(ana,irene).
subordinados(ana,carlos).
subordinados(jose,lorenzo).
subordinados(jose,lizardo).
subordinados(lorenzo,omar).
subordinados(lizardo,paco).
% Reglas
subordinado(Persona, Subordinado) :-
subordinados(Persona, Subordinado).
subordinados_de(Persona) :-
write('Los subordinados de '), write(Persona), write(' son:'), nl,
subordinado(Persona, Subordinado),
write(Subordinado), nl,
fail.
subordinados_de(_).
#!/usr/bin/swipl -q -t volar -f
% reglas
vuela(X) :- puede_volar(X).
% hechos
puede_volar(pajaro).
puede_volar(avion).
no_puede_volar(perro).
no_puede_volar(tortuga).
#!/usr/bin/swipl -q -t weekend_activity -f
activity(friday, 'september townhall').
activity(saturday, 'learn prolog facts').
activity(sunday, 'learn prolog rules').
weekend(saturday).
weekend(sunday).
weekend_activity(A) :-
activity(D, A),
weekend(D).
answer :-
weekend_activity(X),
tab(2), write(X), nl,
fail.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment