Jack's Xtreme Prolog (5-8)

108
Jack’s Xtreme Prolog Eugenio Jacobo Hernández Valdelamar Sesiones 5-8 Versión original: 2001 Reedición: 2010

description

Eugenio Jacobo Hernández Valdelamar. Notas para un curso de Prolog. Sesiones 5-8. Versión remasterizada 2010.

Transcript of Jack's Xtreme Prolog (5-8)

Page 1: Jack's Xtreme Prolog (5-8)

Jack’s Xtreme Prolog

Eugenio Jacobo Hernández Valdelamar

Sesiones 5-8Versión original: 2001

Reedición: 2010

Page 2: Jack's Xtreme Prolog (5-8)
Page 3: Jack's Xtreme Prolog (5-8)

Presentación• En 2001 tuve la oportunidad de impartir un curso de Prolog en la Fundación

Arturo Rosenblueth. En realidad, fuera del Bratko (que es como el vade mecum de Prolog), no tenía mucho material a la mano. Gracias a que muchas personas fueron publicando en el Internet, fue que pude integrar mis notas de clase, materiales y la bibliografía disponible.

• El resultado es una colección de presentaciones que tratan de responder muchas preguntas comunes de cualquiera que toma un curso de este tipo.

• Durante algún tiempo los puse como disponibles en un grupo de Yahoo (donde la mayoría de los asistentes querían que se les resolviera la tarea), pero es hora de moverlos a Scribd para que la comunidad los aproveche.

• Prolog es un lenguaje muy interesante y una herramienta útil para inducirse en lo que podemos llamar inteligencia artificial clásica y aplicar conceptos como el de sistemas expertos; ojala esto sirva para que más personas (estudiantes, docentes y entusiastas) lo descubran y aprovechen.

• Eugenio Jacobo Hernández Valdelamar. Junio, 2010.

Page 4: Jack's Xtreme Prolog (5-8)

Contenido

5. Tipos de datos y recursividad

6. Listas y operadores

7. Operadores

8. !(predicado de corte)

Page 5: Jack's Xtreme Prolog (5-8)

5:Tipos de datos y recursividad

Jacobo Hernández Valdelamar

Xtreme Prolog

Page 6: Jack's Xtreme Prolog (5-8)

Contenido

• Tipos de datos

• ¿Qué es recursividad?

• Recursividad en Prolog

Page 7: Jack's Xtreme Prolog (5-8)

Tipos de datos

• Todos sabemos que los datos que maneja Prolog son los términos. Sin embargo, podemos construir otros tipos de datos a partir de estos. De hecho, algunos están predefinidos para mayor gloria del programador, son el caso de las listas y las cadenas de caracteres.

• En cualquier caso, el lector debe asumir que Prolog no es un lenguaje tipeado, puesto que no existen declaraciones explícitas de tipo tal y como ocurre en los lenguajes imperativos. El hecho de que no existan dichas declaraciones se debe sencillamente a que no hacen falta.

Page 8: Jack's Xtreme Prolog (5-8)

Constantes

• Las constantes en Prolog son términos con aridad cero (átomos). A pesar de su simpleza, pueden ser muy útiles para representar información ya que pueden contener cualquier caracter. Se utilizan, por ejemplo, para representar nombres de archivos

• Recuerde que las constantes numéricas también son términos cero-arios (pero no son átomos).

Page 9: Jack's Xtreme Prolog (5-8)

Registros

• Los registros son agrupaciones ordenadas de datos que en Prolog podemos escribir como términos que almacenan cada dato en un argumento. Por ejemplo, supongamos que queremos un registro para representar los datos personales de la gente:

• persona('Eva','Fina','Y Segura',15) • persona('Fulanito','De Tal','Y Tal',32) • Mediante el término persona/4 representamos a un individuo.

El primer argumento es el nombre, el segundo y tercero son los apellidos y el cuarto es la edad.

• Puesto que los términos son anidables podemos crear registros complejos:

• persona('Menganito',edad(32),direccion('Leganitos',13,'Madrid'))

Page 10: Jack's Xtreme Prolog (5-8)

Árboles

• Puesto que los términos pueden ser recursivos es fácil crear estructuras de datos recurrentes. Como ejemplo, veamos como definir árboles binarios. Para ello representamos el árbol vacío mediante una constante, por ejemplo, empty/0, y un nodo cualquiera puede ser representado mediante el término tree/3.

• El primer argumento representa un dato cualquiera asociado al nodo. El segundo argumento representa la rama izquierda, y el tercer argumento la correspondiente rama derecha. Son ejemplos de árboles:

• empty • tree(dato1,empty,empty)

tree(dato1,tree(dato2,empty,empty),tree(dato3,empty,empty)) tree(dato4,empty,tree(dato5,tree(dato6,empty,empty),empty))

Page 11: Jack's Xtreme Prolog (5-8)

Listas

• Las listas en Prolog podrían definirse del mismo modo que los árboles puesto que los términos se pueden anidar todas las veces que sea necesario.

• Por ejemplo, la lista de números del uno al cinco se puede representar así: – lista(1,lista(2,lista(3,lista(4,lista(5,vacio)))))

• Afortunadamente, las listas están predefinidas en el lenguaje para una mayor comodidad. De modo que la lista anterior la podemos escribir así:

• [1, 2, 3, 4, 5]

Page 12: Jack's Xtreme Prolog (5-8)

Listas (2)

• Esta es la forma de escribir las listas definiendo todos los elementos, pero podemos manipular las listas distinguiendo cabeza y resto: [C|R]. Donde la variable C representa la cabeza, y R el resto. Por ejemplo: – L = [1, 2, 3, 4, 5], – M = [0|L].

• La lista M sería equivalente a [0,1,2,3,4,5] . Es importante no confundir los términos [C|R] y [C,R]. La diferencia es muy sutil: – L = [1, 2, 3, 4, 5], – M = [0,L].

• El resultado sería M = [0,[1,2,3,4,5]], que es una lista de dos elementos.

Page 13: Jack's Xtreme Prolog (5-8)

Listas (3)

• Naturalmente, existe la lista vacía, que se representa como []. Además resulta conveniente tener en cuenta que: – Existen bibliotecas para hacer cosas más

complicadas con las listas, como concatenar, aplanar, etc.

– Los elementos de las listas son términos y pueden ser heterogéneos. Por ejemplo: [1,p(a),[a,b],f(g(h))].

– Las listas también son términos, solamente las escribimos de una manera más cómoda. Así, la lista [1,a,2] es en realidad el término '.'(1,'.'(a,'.'(2,[]))).

Page 14: Jack's Xtreme Prolog (5-8)

Cadenas de caracteres

• Las cadenas de caracteres son en Prolog listas de códigos ASCII.

• Afortunadamente se pueden escribir de una manera cómoda poniendo los caracteres entre comillas dobles.

• Por ejemplo, la expresión "ABC" es en realidad la lista [65,66,67]. Así, podemos tratar las cadenas de caracteres como cadenas o como listas según nos interese. Naturalmente, todo el código que nos sirve para listas nos sirve para cadenas. Por ejemplo, el predicado que concatena dos listas támbien sirve para concatenar dos cadenas de texto

Page 15: Jack's Xtreme Prolog (5-8)

Tests de tipo • Si en Prolog no existen declaraciones de tipo, ¿ como demonios estamos

seguros de que un argumento es de un tipo determinado ?. La respuesta está en los tests de tipo. Éstos son predicados que (habitualmente) reciben un dato como argumento y fallan si el argumento no es del tipo esperado.

• Como ejemplo vamos a escribir el test de tipo para comprobar si un argumento es una lista:

• es_una_lista( [] ). • es_una_lista( [ _ | Resto ] ) :-    • es_una_lista(Resto).

• La lista vacía es una lista, y si no, [A|B] será una lista si y sólo si B es una lista. En cuanto a A, nos trae al fresco lo que valga, por eso usamos una variable anónima en el código.

• Ahora podemos comprobar el tipo de un argumento llamando al test de tipo:

• mi_predicado(Lista1,Lista2) :- es_una_lista(Lista1), es_una_lista(Lista2), ...,

Page 16: Jack's Xtreme Prolog (5-8)

Tests de tipo predefinidos

Existen predicados predefinidos para comprobar algunos tipos básicos. Estos son:

PredicadoTest

integer/1 Comprueba si su argumento es un número entero

float/1 Comprueba si el argumento es un número decimal

number/ Comprueba si el argumento es un número (entero o decimal)

atom/1 Comprueba si el argumento es un término cero-ario excluyendo las constantes numéricas

var/1 Comprueba si el argumento es una variable libre

nonvar/1 Comprueba si el argumento está instanciado

ground/1 Comprueba si el argumento es un término que no contiene variables libres (está cerrado)

Page 17: Jack's Xtreme Prolog (5-8)

Anécdota sobre la solución de problemas

• John von Neumann(1903-1957) tenía la costumbre de escribir en la pizarra las soluciones de los problemas que mandaba. Por supuesto, los estudiantes le preguntaban como hacer los problemas, no solo la solución. En cierta ocasión, uno de ellos intentó ser más diplomático y en lugar de preguntarle directamente cómo se hacía el problema, le dijo :- Profesor, ¿este problema se podría hacer de otra forma ?- Déjeme que piense ..., si.Y siguió escribiendo soluciones en la pizarra.

Page 18: Jack's Xtreme Prolog (5-8)

Qué es recursividad?

• An algorithmic technique where a function, in order to accomplish a task, calls itself with some part of the task.

• Note: Recursive solutions involve two major parts: – base case(s), in which the problem is simple enough to be

solved directly, and– recursive case(s).

• A recursive case has three components: – (1) divide the problem into one or more simpler or smaller

parts of the problems, – (2) invoke the function (recursively) on each part, and – (3) combine the solutions of the parts into a solution for the

problem. • Depending on the problem, any of these may be trivial or

complex.

Page 19: Jack's Xtreme Prolog (5-8)

¿Qué es recursividad? (2)

• “Para entender qué es la recursividad, antes hay que entender qué es la recursividad”.

• Tipo de datos RECURSIVO -> Se define en función de sí mismo

• Procedimiento o Función RECURSIVOS -> En su interior se encuentra una llamada al mismo procedimiento o función.

Page 21: Jack's Xtreme Prolog (5-8)

Características de la recursividad

• The big problem that you're trying to solve is the same for every case.

• The big problem can be broken down into a smaller problem.

• There is a point where you know you're done (because there is nothing left to do). This is called the base case, stopping state or stopping condition.

Page 22: Jack's Xtreme Prolog (5-8)

Ejemplo

• The golden string is an infinite non-repetitive binary string. It's a fractal in the sense that it is self similar everywhere. One way to generate it is as follows: Call the initial steps s0 = 0 and s1 = 1.

• For n = 2, 3, 4, ... the step sn is the concatenation of sn-1 and sn-2. So the first steps of the forming of the golden string are

• 0, 1, 10, 101, 10110, 10110101, 1011010110110, 101101011011010110101...

• and as n goes towards infinity, sn is the golden string.

Page 23: Jack's Xtreme Prolog (5-8)

Nota sobre la recursividad

• La recursividad y la iteración (ejecución en bucle) están muy relacionadas, cualquier acción que pueda realizarse con la recursividad puede realizarse con iteración y viceversa. Normalmente, un cálculo determinado se prestará a una técnica u otra, sólo necesita elegir el enfoque más natural o con el que se sienta más cómodo.

Page 24: Jack's Xtreme Prolog (5-8)

Ejemplo (1)

• Construct a computer system to help decide the best route between two U.S. cities

• You will use the final system to investigate questions such as:– Is there a direct road from one particular town

to another?– Which towns are situated less than ten miles

from a particular town?

Page 25: Jack's Xtreme Prolog (5-8)

Ejemplo (2)• road(tampa,houston,200). • road(gordon,tampa,300). • road(houston,gordon,100). • road(houston,kansas_city,120). • road(gordon,kansas_city,130).

• %caso base• route(Town1,Town2,Distance):-

road(Town1,Town2,Distance). • %caso recursivo• route(Town1,Town2,Distance):-

road(Town1,X,Dist1), • route(X,Town2,Dist2), • Distance=Dist1+Dist2.

• ?- route(tampa, kansas_city, D), write(D),nl.

Page 26: Jack's Xtreme Prolog (5-8)

Recursividad en Prolog• Todos los términos en Prolog pueden ser recursivos, y gracias a la unificación,

podemos recorrer sus argumentos a voluntad. La estructura de datos más significativa con respecto a la recursividad son las listas, por eso centraremos nuestros ejemplos en ellas.

• La estructura de las cláusulas de un predicado recursivo es muy simple. Como ejemplo veamos un predicado que calcula la longitud de una lista:

• % La longitud de la lista vacia es cero • longitud([],0). • % La longitud de una lista es la longitud • % del resto mas uno. Como el contenido • % de la cabeza no nos interesa, • % utilizamos la variable anonima • longitud( [_|Resto], Longitud) :- longitud(Resto,LongitudResto), Longitud is

LongitudResto+1.

• Observe como el primer objetivo de la segunda cláusula es una llamada al propio predicado que estamos definiendo. Para evitar que un predicado se llame a sí mismo infinitamente debemos estar seguros de que existe al menos un caso en el que termina. Este caso se contempla en la primera cláusula y se denomina caso básico.

Page 27: Jack's Xtreme Prolog (5-8)

Parámetros de acumulación • La técnica de parámetros de acumulación se suele utilizar en combinación con la

recursividad. Consiste en un argumento auxiliar (o varios de ellos) que almacena la solución parcial en cada paso recursivo. Cuando llegamos al caso base, la solución parcial es la solución total.

• longitud2_aux([],Parcial,Parcial). • longitud2_aux([_|Resto],Parcial,Result) :-

– NParcial is Parcial+1, – longitud2_aux(Resto,NParcial,Result).

• longitud2(Lista,Longitud) :- longitud2_aux(Lista,0,Longitud).

• En este ejemplo, el valor inicial del parámetro de acumulación es cero. Este valor inicial es importante para que la solución sea correcta. Por eso hemos creado el predicado longitud2/2, que se asegura el correcto uso del parámetro de acumulación. El predicado longitud2_aux/3 no debería ser ejecutado directamente.

• La ventaja del parámetro de acumulación es que genera recursividad de cola, esto es, la llamada recursiva es siempre la última en ejecutarse. Esto permite a los compiladores optimizar considerablemente el uso de recursos ocasionado por la recursividad. La desventaja es que los predicados podrían resultar no reversibles.

Page 28: Jack's Xtreme Prolog (5-8)

Ejercicio (1)

• Una forma de calcular el máximo común divisor de dos números enteros positivos es utilizar la siguiente definición recursiva: – mcd (m, n) = m, si m = n. – mcd (m, n) = mcd (m - n, n), si m > n. – mcd (m, n) = mcd (m, n - m) en el resto de los

casos.

• Escribe la función recursiva mcd () que calcula el máximo común divisor de dos números aplicando esta definición.

Page 29: Jack's Xtreme Prolog (5-8)

Ejercicio (2)

• Una empresa nos hace la siguiente oferta de trabajo: – El primer año nos paga $120.000 – El resto de los años tendremos un aumento

de sueldo anual de 4 por ciento sobre lo que estemos cobrando.

• Escribe una función recursiva que calcule el sueldo que tendremos dentro de X años.

Page 30: Jack's Xtreme Prolog (5-8)

Tarea

• Implemente un programa en Prolog que solucione el problema de las Torres de Hanoi, definiendo los siguientes predicados:– hanoi, with one parameter that indicates the total number of

disks you are working with.– move, which describes the moving of N disks from one pole to

another--using the remaining pole as a temporary resting place for disks.

– inform, which displays what has happened to a particular disk.– loc =right;middle;left – PREDICATES

• hanoi(integer) • move(integer,loc,loc,loc) • inform(loc,loc)

Page 31: Jack's Xtreme Prolog (5-8)

Referencias

• Tres formas diferentes de explicar la recursividad http://www.di-mare.com/adolfo/p/recurse1.htm

• Apuntes en la facu http://www.lafacu.com/apuntes/informatica/

• Curso intermedio de programación en Prolog http://www.programacion.com/cursos/prolog2/

• Recursion http://selkirk.nic.edu/~mann/cs160/Recurs/index.html

• Removing the “Curse” from Recursion http://www.dulcian.com/slides/speeches/PD%20Removing%20the%20Curse%20from%20Recursion%20mini/index.htm

• The sounds of math http://www.geocities.com/vienna/9349/recursion.html

Page 32: Jack's Xtreme Prolog (5-8)

Referencias (2)

• The Tao of Recursion http://www.schnada.de/hylin/tao.html

Page 33: Jack's Xtreme Prolog (5-8)

6:Listas y operadores

Xtreme Prolog

Jacobo Hernández Valdelamar

2001

Page 34: Jack's Xtreme Prolog (5-8)

Contenido

• Manejo avanzado de listas– Unificación– Patrón [V1|V2]– Variables sin nombre

• El predicado if..then..else

• Definición de operadores– La relación op()

Page 35: Jack's Xtreme Prolog (5-8)

Unificación en las listas

• [a,b,c] unifies with [Head|Tail] resulting in Head=a and Tail=[b,c]

• [a] unifies with [H|T] resulting in H=a and T=[] • [a,b,c] unifies with [a|T] resulting in T=[b,c] • [a,b,c] doesn't unify with [b|T] • [] doesn't unify with [H|T] • [] unifies with []. Two empty lists always match

Page 36: Jack's Xtreme Prolog (5-8)

Ejemplos de unificación con listas

• ?- [a,b,c]=[a,b,c]. %ok• ?- [a,b]=[a,b,c]. %no• ?- [A|B]=[a,b,c], write(A),write(B). • ?- [a|C]=[a,b,c], write(C). • ?- [A|B]=[], write(A),write(B). • ?- []=[]. • ?- [person(X)|Rest] = [person(fred),

person(joe)], write(X).

Page 37: Jack's Xtreme Prolog (5-8)

Patrón [V1|V2] y variables sin nombre

• The “|”' can follow several items, and occur within a sublist. The bit after the “|”' should always match the rest of the list.

• unnamed variable "_''. It is convenient (and good style) to use this variable name for things we don't care about.

Page 38: Jack's Xtreme Prolog (5-8)

Caracter declarativo

• Declarative character of many Prolog programs enables one to use the same procedure in different ways. Note, that it is not distinguished whether the argument of the procedure is input or output in Prolog. Thus, it is possible to use one argument as input in one call and use the same argument as output in other call. See following example:

– member(X,[X|T]).– member(X,[_|T]):-member(X,T).– – ?-member(1,[1,2,3]). % usage as a test– ?-member(X,[1,2,3]). % usage as a member generator (returns successively

X=1, X=2, X=3)– ?-member(1,L). % usage as a list generator (returns L=[1|_], L=[_,1|_],

L=[_,_,1|_] etc.)– ?-member(X,L). % generator of general lists containing X (returns L=[X|_],

L=[_,X|_], L=[_,_,X|_] etc.)

Page 39: Jack's Xtreme Prolog (5-8)

Ejemplo

• %----------------append/3• % caso en que la primer lista es vacia• append([],R,R).

• % la idea de agregar una lista a otra es mantener la cabeza de la primera lista, y unir la cola de la primera con la segunda lista

• append([H|T],L2,[H|R]):- append(T,L2,R).

• %?-append([1,2,3],[4,5],X), write(X). • [1,2,3,4,5]

Page 40: Jack's Xtreme Prolog (5-8)

Ejercicio

• Implementa la relación – max(Lista,MaxAcum,Resultado)

• El objetivo es localizar el valor máximo de una lista de numeros

• ?- max([1,3,45,6,7,81,76],0,Res).

• 81

Page 41: Jack's Xtreme Prolog (5-8)

Ejercicio

• Implementar las relaciones necesarias para invertir el orden de los elementos de una cadena (reverse/3):– reverse(InitList,L,Result).

– ?- reverse([1,2,3],[],R).– [3,2,1]

Page 42: Jack's Xtreme Prolog (5-8)

Ejemplo: ordenaciones

• Insert sort is a traditional sort algorithm.

• Prolog implementation of insert sort is based on idea of acumulator.

• %----------------insert sort

• insert_sort(List,Sorted):-i_sort(List,[],Sorted).

• i_sort([],Acc,Acc).• i_sort([H|T],Acc,Sorted):-

insert(H,Acc,NAcc),i_sort(T,NAcc,Sorted).• • insert(X,[Y|T],[Y|NT]):-X>Y,insert(X,T,NT).• insert(X,[Y|T],[X,Y|T]):- X=<Y.• insert(X,[],[X]).

• ?- insert_sort([9,8,6,4,3,2,1],Res), write(Res).

• [1,2,3,4,6,8,9]Yes.

Page 43: Jack's Xtreme Prolog (5-8)

A1, ... , An -> B1, ... , Bm else C1, ... . CkA1, ... , An -> B1, ... , Bm

• The predicate -> (if-then-else) executes first the left goal A1, ... , An and if it succeeds then executes the middle goal - B1, ... , Bm, if it fails then executes the right goal - C1, ... , Ck. If the right goal is missing then this is the same as if it was the empty goal. In this predicate you can write ; instead of else. This is for compatibility with other Prolog compilers.

• If you write: ?-a->b->c;d;e.

• then the last ; will be accepted not as a part of if-then-else but as an operator or.

• If you want to create more complicated expression with many if-then-else operators in it - then use round brackets - ( and ).

• Like this: ?-a-> (b->c;d);e.

• Be careful, in this case, to leave a space between -> and ; and (, otherwise you can obtain the error No sense.

• Look also at the function -> (if-then-else).

Page 44: Jack's Xtreme Prolog (5-8)

Ejemplo

• ?- yes_no("1","",?) -> • (yes_no("2","",?) ->• write(a), nl• else• write(b), nl• )• else (yes_no("3","",?) ->• write(c), nl• else• write(d), nl• ).

Page 45: Jack's Xtreme Prolog (5-8)

Operadores

• Operators simplify entry of Prolog programs. They are only used to define syntactic conventions of program and data entry.

• The definition of operators helps Prolog to understand expression like 1+2+3*4 which is translated into notation +(+(1,2),*(3,4)).

Page 46: Jack's Xtreme Prolog (5-8)

op(Priority, Type, Operator)• Priority Priority of the operator. Smaller numbers specify higher priority.• Type Type of the operator.• Operator Operator sign• Operator types:

• fx, fy unary, the argument follows e.g.: ‘minus X’ as -X• xf, yf unary, after the argument e.g.: ‘factorial N’ as N!• xfx, yfy, xfy, yfx binary, between the arguments e.g.: +, -, *, /• x and y letters specify associativity:

• x the main operator in the operand must be of higher priority than this operator• y the main operator in the operand must be of higher or equal priority than this

operator

• Thus yfx denotes an operator which will be evaluated from left to right (such as + or *), and xfy denotes an operator which will be evaluated from right to left (such as ;), and xfx denotes an operator which is not associative (it can be placed only between arguments with the main operators of higher priority) such operators are >, < and yfy denotes an operator which is right and left associative. Usually people do not use the last type because it gives double sense.

• If you want to use an operator in the source then it should be defined as an axiom which is before the row where you want to use it or you can put the op operator in the body of a clause but in the second case this definition will take effect only after that this clause is executed.

Page 47: Jack's Xtreme Prolog (5-8)

Tarea

• Implementar los siguientes algoritmos de ordenamiento:– Burbuja– Quick sort

Page 48: Jack's Xtreme Prolog (5-8)

Tarea (2)• Usando la siguiente base de hechos,

implementa las relaciones:

• madre(X,Y).• padre(X,Y).• es_madre(X,Y).• es_padre(X,Y).• hijo(X,Y).• hija(X,Y).• descendiente(X,Y).• ancestro(X,Y)

• Extiende la base para poder implementar relaciones como tio, tia, abuelo, abuela, primo, etc.

• man(adam). • man(peter). • man(paul). • woman(marry). • woman(eve).

• %relation "parent" associates parent and child.

• parent(adam,peter). • parent(eve,peter). • parent(adam,paul). • parent(marry,paul).

Page 49: Jack's Xtreme Prolog (5-8)

Tarea (3)

• Entrega en 2 semanas (en la semana 8)• Modela e implementa el funcionamiento

de la máquina de Turing• turing(State,Tape,Tape), donde se da un

estado inicial, una cinta con valores y se obtiene una cinta al final del proceso

Page 50: Jack's Xtreme Prolog (5-8)

7: Operadores

Xtreme Prolog

Jacobo Hernández Valdelamar

2001

Page 51: Jack's Xtreme Prolog (5-8)

Contenido

• Caso de estudio de listas:– Evaluación de expresiones

• Definición de operadores

• Uso de operadores– Caso de estudio: derivación simbólica

Page 52: Jack's Xtreme Prolog (5-8)

Caso de estudio: evaluación de expresiones

• Para evaluar una expresión, necesitamos saber su gramática

• Ej. Sujeto-verbo-predicado– Sujetos – nombres propios, sustantivos.– Verbos- acciones– Predicados – sustantivos, adjetivos, etc.

• Prolog permite hacer esto de forma sencilla y clara

Page 53: Jack's Xtreme Prolog (5-8)

Simple English Syntax

• The components of this simple syntax will be such categories as sentences, nouns, verbs etc. Here is a (top down) description: – Unit: sentence Constructed from: noun phrase followed by a

verb phrase – Unit: noun phrase – Constructed from: proper noun or determiner followed by a noun – Unit: verb phrase – Constructed from: verb or verb followed by noun phrase – Unit: determiner Examples: a, the – Unit: noun Examples: man, cake – Unit: verb Examples: ate

Page 54: Jack's Xtreme Prolog (5-8)

Ejemplo de una oración basada en la gramática sencilla del ingles

Page 55: Jack's Xtreme Prolog (5-8)

Evaluación de expresiones de una gramática sencilla

• % A simple grammar - rules• % s - sentence np - noun part

vp - verb part v - verb• %• s(Z) :- np(X), vp(Y), append(X,Y,Z).• vp(Z) :- v(X), np(Y), append(X,Y,Z).• vp(Z) :- v(Z).

• % lexicon• %• np(["Dr. Chan"]).• np(["MediCenter"]).• np([nurses]).• np([patients]).• v([died]).• v([employed]).

• % append/3

• append([],R,R).• append([H|T],L2,[H|R]):- append(T,L2,R).

• %• % examples• %• test1 :- s([patients,died]).• test2 :-

s(["MediCenter",employed,nurses]).• test3:- s(["Dr. Who", nurses, died]).

• ?- test1.• ?- test2.• ?- test3.

Page 56: Jack's Xtreme Prolog (5-8)

Solución 2• sentence(S):- append(NP,VP,S), • noun_phrase(NP), • verb_phrase(VP).

• noun_phrase(NP):- • append(Det,Noun,NP), • determiner(Det), • noun(Noun).

• verb_phrase(VP):- • append(Verb,NP,VP), • verb(Verb), • noun_phrase(NP).• • determiner([a]). • determiner([the]).

• noun([man]). • noun([cake]).

• verb([ate]).

• Here is what happens to the query: • ?- sentence([the,man,ate,the cake]).• append/3 succeeds with NP=[],

VP=[the,man,ate,the,cake] • noun_phrase/1 fails • append/3 succeeds with NP=[the],

VP=[man,ate,the,cake] • noun_phrase/1 fails • append/3 succeeds with NP=[the,man],

VP=[ate,the,cake] • noun_phrase/1 succeeds • ... • verb_phrase/1 succeeds

Page 57: Jack's Xtreme Prolog (5-8)

Ejercicio

• Agrega al ejemplo anterior elementos gramaticales como pronombres , adjetivos, etc.

Page 58: Jack's Xtreme Prolog (5-8)

Operadores

• Operators are special Prolog structures that have operator signs as their names. Since they are structures, operators are word-like entities in the Prolog language.

• The Prolog interpreter treats operator signs as special atoms that can be the names of structures. Operators can be represented according to the customary format for structures, that is, by writing the structure name followed by its arguments, with these being enclosed in parentheses and separated by commas. Thus, an operator can be represented as

• op_sign(op1, op2) where the operator sign, op_sign, is followed by its operands, op1 and op2.

Page 59: Jack's Xtreme Prolog (5-8)

Operadores (2)

• For example, the name of the addition operator is the plus sign, "+". The operands of the addition operator, that is, the numbers that are to be added together, are the arguments of the structure named by the plus sign. Hence, the addition of two numbers, such as 3 and 4, can be represented as follows: – +(3, 4)

• The arguments or operands of an arithmetic operator such as addition must, of course, be numbers.

Page 60: Jack's Xtreme Prolog (5-8)

Como encontrar operadores ya definidos

• ?- current_op(X,Y,+).

• X=500

• Y=fx ;

• X=500

• Y=yfx

Page 61: Jack's Xtreme Prolog (5-8)

op(Priority, Type, Operator)• Priority Priority of the operator. Smaller numbers specify higher priority.• Type Type of the operator.• Operator Operator sign

• Operator types:

• fx, fy unary, the argument follows e.g.: ‘minus X’ as -X• xf, yf unary, after the argument e.g.: ‘factorial N’ as N!• xfx, yfy, xfy, yfx binary, between the arguments e.g.: +, -, *, /• x and y letters specify associativity:

• Thus yfx denotes an operator which will be evaluated from left to right (such as + or *), and xfy denotes an operator which will be evaluated from right to left (such as ;), and xfx denotes an operator which is not associative (it can be placed only between arguments with the main operators of higher priority) such operators are >, < and yfy denotes an operator which is right and left associative. Usually people do not use the last type because it gives double sense.

• If you want to use an operator in the source then it should be defined as an axiom which is before the row where you want to use it or you can put the op operator in the body of a clause but in the second case this definition will take effect only after that this clause is executed.

Page 62: Jack's Xtreme Prolog (5-8)

Ejemplo: or/2

• For or/2 we choose precedence of 950 (less than and/2) and associativity of xfy (the same as and/2) with: – op(950,xfy,or)

• and define it as equivalent to:– X or Y :- call(X). – X or Y :- call(Y).

Page 63: Jack's Xtreme Prolog (5-8)

Ejemplo

• Derivación de funciones• ¿Qué necesitamos?

– Saber que las entradas son numéricas– Evaluar expresiones– Implementar las reglas de derivación

• P.ej. Sabemos que – d(c)=0 , d(x)=1– d(u+v)=d(u)+d(v) , d(u-v)=d(u)-d(v)

• Qué pasa si queremos implementar un operador de exponentes?

Page 64: Jack's Xtreme Prolog (5-8)

Ejemplo de uso de operadores• The goal d(E1, X, E2) is true if expression E2 is a possible form for

the derivative of expression E1 with respect to X.

• op(300, xfy, ***).

• d(X, X, D) :- atomic(X), !, D = 1.• d(C, X, D) :- atomic(C), !, D = 0.• d(U+V, X, DU+DV) :- d(U, X, DU), d(V, X, DV).• d(U-V, X, DU-DV) :- d(U, X, DU), d(V, X, DV).• d(U*V, X, DU*V+U*DV) :- d(U, X, DU), d(V, X, DV).• d(U***N, X, N*U***N1*DU) :- integer(N), N1 is N-1, d(U, X, DU).• d(-U, X, -DU) :- d(U, X, DU).

Page 65: Jack's Xtreme Prolog (5-8)

No necesariamente se usan pues las relaciones pueden hacer el

trabajo• termino(x).

• d(C,_,R):-integer(C),!,R is 0.• d(X,X,R):- termino(X),!,R is 1.

• d(plus(U,V),X,plus(U1,V1)):-• d(U,X,U1),• d(V,X,V1).• d(minus(U,V),X,minus(U1,V1)):-• d(U,X,U1),• d(V,X,V1).• d(mult(U,V),X,plus(mult(U1,V),mult(U,V1))):-• d(U,X,U1),• d(V,X,V1).• d(div(U,V),X,div(minus(mult(U1,V),mult(U,V1)),

mult(V,V))):-• d(U,X,U1),• d(V,X,V1).

• d(ln(U),X,mult(div(integer(1),U),U1)):- d(U,X,U1).

• d(potens(E1,I),X,mult(mult(integer(I),potens(E1,integer(I1))),EXP)):-

• I1 is integer(I)- 1, • d(E1,X,EXP).• d(sin(U),X,mult(cos(U),U1)):- d(U,X,U1). • d(cos(U),X,minus(integer(0),mult(sin(U),U1))):-

d(U,X,U1).• d(tan(U),X,mult(potens(sec(U),integer(2)),U1)):-

d(U,X,U1).

• ?- d(tan(x),x,D),write(D).

Page 66: Jack's Xtreme Prolog (5-8)

Tarea

• Investigar como funciona Elisa• Implementar una gramática cualquiera

(incluir especificación BNF)• Implementar un programa en Prolog que

permita integrar funciones. El ejercicio consiste en implementar las reglas inversas del programa de derivación.

Page 67: Jack's Xtreme Prolog (5-8)

Referencias

• Karl's Calculus Tutor http://www.karlscalculus.org/calculus.html

• HMC Math Tutorials http://www.math.hmc.edu/calculus/tutorials/

• e-Calculus http://www.math.uakron.edu/~dpstory/e-calculus.html

• Prolog Notes http://web.uvic.ca/~esg02/ling482/Prolog/operators.html

Page 68: Jack's Xtreme Prolog (5-8)

Referencias (2)

• Prolog Operators http://www.cs.sfu.ca/CC/SW/Prolog/Notes/operator.html

Page 69: Jack's Xtreme Prolog (5-8)

8: !(predicado de corte)

Xtreme Prolog

Jacobo Hernández Valdelamar

2001

Page 70: Jack's Xtreme Prolog (5-8)

Contenido

• ¿Qué es el ! ?• ¿Para qué sirve el corte?• Efectos del uso del corte• Propositos del predicado de corte• Caso de estudio: sistemas expertos

– Caracteristicas y arquitectura– Metodologia de desarrollo– Representación del conocimiento– Micro sistema experto

Page 71: Jack's Xtreme Prolog (5-8)

¿Qué es el !(cut)?

• Cut is a feature of Prolog (not logic programming) that is used to cut alternative branches of computation and, thus, these branches are not explored by backtracking.

Page 72: Jack's Xtreme Prolog (5-8)

¿Para qué sirve?

• Cut puede mejorar la eficiencia de los programas en Prolog, sin embargo, también cambia el comportamiento operacional de los programas.

• Debe usarse "cut" con cuidado, pues los programas que lo contienen, por lo general son más difíciles de leer.

Page 73: Jack's Xtreme Prolog (5-8)

Ejemplos básicos

– % returns X=1,X=2,X=3,X=4 successively– ?-member(Y,[[1,2],[3,4]]),member(X,Y).

– % returns X=1 only– ?-member(Y,[[1,2],[3,4]]),member(X,Y),!.

– % returns X=1, X=2 successively– ?-member(Y,[[1,2],[3,4]]),!,member(X,Y).

– % returns X=1,X=2,X=3,X=4 successively– ?-!,member(Y,[[1,2],[3,4]]),member(X,Y).

Page 74: Jack's Xtreme Prolog (5-8)

Efectos del corte• % Sin corte. • p(X,Y) :- • X > 15, • Y > 50. • • p(X,Y) :- • X > Y,

• Veamos que ocurre si ejecutamos el objetivo p(25,12): – Observe que ambas cláusulas unifican con la cabeza, luego

existen dos puntos de elección que se anotan. – Prolog entra por el primer punto de elección (primera

cláusula) eliminándolo. – Prolog ejecuta el primer objetivo del cuerpo (X>15), que

tiene éxito. – Prolog ejecuta el segundo objetivo del cuerpo (X>50), que

falla. – Empieza el backtracking. – Se recorren ambos objetivos hacia atrás pero no hay

variables que se hayan ligado en ellos. – Encontramos el segundo punto de elección (segunda

cláusula) que detiene el backtracking eliminándolo en el proceso. La ejecución continúa hacia delante.

– Prolog ejecuta el cuerpo de la segunda cláusula que consiste en X>Y. Este objetivo tiene éxito.

– El objetivo p(25,12) tiene éxito.

Page 75: Jack's Xtreme Prolog (5-8)

Efectos del corte (2)• % Con corte.• q(X,Y) :- • X > 15, • !, • Y > 50. • • q(X,Y) :- • X > Y,

• Ahora comprobamos lo que ocurre cuando existe el corte, ejecutamos q(25,12):

– Ambas cláusulas unifican con la cabeza, luego existen dos puntos de elección que se anotan.

– Prolog entra por el primer punto de elección (primera cláusula) eliminándolo.

– Prolog ejecuta el primer objetivo del cuerpo (X>15), que tiene éxito.

– Se ejecuta el segundo objetivo del cuerpo que es el corte. Por tanto, se eliminan todos los puntos de elección anotados que son debidos al objetivo q(25,12). Solamente teníamos uno, que se elimina.

– Prolog ejecuta el tercer objetivo del cuerpo (X>50), que falla.

– Empieza el backtracking. – Se recorren ambos objetivos hacia atrás pero no hay

variables que se hayan ligado en ellos. – No encontramos ningún punto de elección porque fueron

eliminados por el corte. – El objetivo p(25,12) falla.

Page 76: Jack's Xtreme Prolog (5-8)

Más del !!• Cut (i.e. !) is a predicate which "cuts" away nondeterminism, i.e. "cuts" away

the possibility for further solutions (hence the name).• The nondeterminism it cuts away can be divided into two groups (though

some cuts will fall into both groups):– Cut's that cut away the possibility to backtrack into a subsequent clause of the

current predicate.– Cut's that cut away further solutions to a nondeterministic predicate call.

• There are no other (sensible) uses of a cut, except for the two mentioned above. Once these purposes are understood it is easy to put cuts in the right place:

– Either the cut is put at a place where backtrack to subsequent clauses is no longer wanted, or/and

– It is put after the call of a nondeterministic (i.e. nondeterm or multi) predicate call, for which only a single solution is important.

Page 77: Jack's Xtreme Prolog (5-8)

Ejemplo de corte del backtracking

• p(17, X) :-• X > 13,• !,• q(X),• ...• p(A, X) :-• ...• In this example we have a cut after the test for X > 13. this is a very

typical sound use of the first reason: "Our clauses cases out on the input and now (where now is immediately after the test X > 13), we have found the right case".

• Such a cut is typically placed just after the head of the clause or after a test close to the head of the clause.

Page 78: Jack's Xtreme Prolog (5-8)

Ejemplo de corte en predicados no deterministas

• firstMember(X, L) :-• member(X, L),• !.• In this example the cut is placed immediately

after a nondeterministic predicate, of which we are only interested in a single solution.

• Above I have highlighted the word immediately twice, and this is because the keyword in placing cuts is immediately: they should be placed as early in the clause as possible.

Page 79: Jack's Xtreme Prolog (5-8)

OJO

• You should be suspicious about clauses containing more that one cut. More than one cut in a single clause often signals a programming or design error.

Page 80: Jack's Xtreme Prolog (5-8)

Caso de estudio: sistemas expertos

Page 81: Jack's Xtreme Prolog (5-8)

Introducción

• Systems that can replace human experts – under certain conditions – in restricted areas

• Expert systems can – represent heuristics and uncertain information – reason under uncertainty – explain their reasoning and results

Page 82: Jack's Xtreme Prolog (5-8)

Caracteristicas

• separate control and knowledge

• contains expert knowledge

• uses symbolic reasoning

• may reason heuristically

• may use inexact reasoning

Page 83: Jack's Xtreme Prolog (5-8)

Problemas para la que son buenos los SEs

• Interpretation (weather data) • Prediction (weather forecast) • Diagnosis • Design • Planning • Debugging and repair • Instruction (tutoring) • Surveillance (discovery of discrepancies) • Control (correction of discrepancies)

Page 84: Jack's Xtreme Prolog (5-8)

Metodología para el desarrollo de un SE

• Steps to perform :– Problem identification – Knowledge formulation and prototyping – Implementation of a complete system – Testing and evaluation – Installation and system integration – Continued maintenance

Page 85: Jack's Xtreme Prolog (5-8)

Sistemas expertos (arquitectura)

Page 86: Jack's Xtreme Prolog (5-8)

Design goals

• use natural reasoning strategies such as if..then, “if the light doesn’t come on, check the bulb”

• capturing the knowledge base can be separate from implementing the inference engine

• the same inference engine can be applied to a variety of problem domains

• modularity allows us to test different control strategies to obtain the best results

Page 87: Jack's Xtreme Prolog (5-8)

Integración de SEs y objetos

Page 88: Jack's Xtreme Prolog (5-8)

Representación del conocimiento

• Types of knowledge • declarative knowledge

– concepts, objects and facts describe what is known about the problem• procedural knowledge

– rules, strategies, procedures and agendas describe how the problem is solved

• heuristic knowledge– rules of thumb that are used when solving the problem

• structural knowledge– rule sets, concept relationships and concept to object relationships that

describe knowledge structures• meta knowledge

– knowledge about all the other types of knowledge and how to use them

Page 89: Jack's Xtreme Prolog (5-8)

Técnicas de representación

• Object-attribute-value triplets are used to represent facts.

Page 90: Jack's Xtreme Prolog (5-8)

Representación (2)

• Uncertain facts certainty factors are used to represent the degree of believe in a fact.

Page 91: Jack's Xtreme Prolog (5-8)

Representación (3)

• Fuzzy sets another kind of uncertainty is caused by ambiguity

Page 92: Jack's Xtreme Prolog (5-8)

Representación (4)

• Rules rules represent relations that link known information to information that can be concluded or inferred from it.

• if the teacher of a class will teach in swedishthen choose that class

• conclusions of rules may have uncertainty:

• if the teacher has a sense of humorthen that class will be fun CF=0.8

Page 93: Jack's Xtreme Prolog (5-8)

Representación (5)

• Semantic networks a graphical representation consisting of nodes (objects, object properties or property values) and arcs (relationships between arcs). Property values are inherited via is-a links.

Page 94: Jack's Xtreme Prolog (5-8)

Representación (6)• Frames a frame is a data structure that represents stereotypical knowledge on

some concept or object

Frame name: Teacher at DSVProperties: Teaches unknownHas sense of humor noTeaches in Swedish

Frame name: HarkoClass: Teacher at DSVProperties: Teaches kurs38Has sense of humor noTeaches in English

Frame name: HaraldClass: Teacher at DSVProperties : Teaches kurs38Has sense of humor yesTeaches in Swedish

Page 95: Jack's Xtreme Prolog (5-8)

Representación (7)

• Logic logic is the oldest form of knowledge representation in computers

• 2 kinds of logic are most often used in intelligent systems:– propositional logic– predicate logic

Page 96: Jack's Xtreme Prolog (5-8)

Caso de estudio: micro sistema experto

Operadores parasimplificar la

definición de reglas del SE

Base de Conocimientodel contexto

Casos de Prueba

Shell (motor de inferencia)

Utilerias

Page 97: Jack's Xtreme Prolog (5-8)

Soporte para la declaración de reglas

• % OPERATOR DECLARATIONS

• op(975, fx, if).

• op(950, xfy, then).

• op(925, xfy, and).

• op(900, fx, not).

Page 98: Jack's Xtreme Prolog (5-8)

Base de reglas y hechos• % EXPERT SYSTEM RULES AND FACTS (Example Knowledge

Bases)

• % Knowledge Base 1: Checking if something is a suitable pet..

• rule(if eats(Animal, Food) and living(Food) then carnivore(Animal)).• rule(if carnivore(Animal) and big(Animal) then dangerous(Animal)).• rule(if has_feathers(Animal) then bird(Animal)).• rule(if bird(Animal) and small(Animal) then good_pet(Animal)).• rule(if cuddly(Animal) then good_pet(Animal)).

Page 99: Jack's Xtreme Prolog (5-8)

Traducción de preguntas a idioma natural

• % TEXT TEMPLATES FOR ENGLISH

• % qtext/2: Provides a simple template based translation into English • % questions.

• % KB1• qtext(cuddly(X), ["Is ", X, " cuddly?"]).• qtext(has_feathers(X), ["Does ", X, " have feathers?"]).• qtext(small(X), ["Is ", X, " small?"]).

• % atext/2: Template based translation into recommendations.

• atext(good_pet(P), ["I suggest that ", P, " would make a good pet."]).

Page 100: Jack's Xtreme Prolog (5-8)

Caso de prueba

• % EXAMPLE TEST CASES

• find_good_pet:- • check_hypotheses([good_pet(lenny),

good_pet(eddie), good_pet(tweety)]).

• La pregunta: una vez implementado esto, Prolog se encarga de la inferencia?

Page 101: Jack's Xtreme Prolog (5-8)

NO…

• Prolog se encarga de interpretar las intrucciones y permitir la creación de la base de conocimiento

• Es necesaria la implementación del motor de inferencia y el sistema de explicación (en este caso este último no se implementa)

Page 102: Jack's Xtreme Prolog (5-8)

El shell• % MAIN EXPERT SYSTEM SHELL CODE

• % check_hypotheses(+Hypotheses)• % Succeeds when one of the hypotheses is proved true, or it• % has tried them all.• % Picks a hypothesis, and uses b_chain to find out if it is true.• % If it is true then b_chain succeeds and check_hypothesis writes out the• % appropriate recommendation. If false it backtracks to 'member' • % to find another hypothesis to try.• % Once it has tried all the hypotheses it will backtrack to second• % check_hypothesis clause and write an appropriate message.

• check_hypotheses(Hypotheses) :-• member(Hypoth, Hypotheses), % get a member of hypotheses• bchain(Hypoth), !, % b_chain to check if true.• atext(Hypoth, Text), % get hold of appropriate text.• write_list(Text). % write out the recommendation

• check_hypotheses(_) :- write_list(["None of the possible hypotheses seem to be true"]).

Page 103: Jack's Xtreme Prolog (5-8)

Estrategias de inferencia

• Estrategias para la solución de problemas:– Encadenamiento hacia delante (foreward

chaining):• es el razonamiento desde los hechos hacia las

conclusiones que resultan de ellos.

– Encadenamiento hacia atrás (backward chaining):• implica el razonamiento en reversa desde una hipótesis

que habrá de comprobarse llegando a una conclusión, a los hechos que la sustentan

Page 104: Jack's Xtreme Prolog (5-8)

Backward chaining• % bchain(+Fact)• % Succeeds if Fact is true, given rules + facts supplied by user as• % backward chaining proceeds.

• bchain(F1 and F2):- !, % F1 and F2 are true if• bchain(F1), % F1 can be proved by backward chaining • bchain(F2). % and F2 can be too.

• bchain(Fact) :- % Fact's true if its a fact!• kbfact(_,Fact), !.• bchain(Fact) :-• kbfact(_, not Fact), !, fail. % But its not if its negation is true.

• bchain(not Fact) :- • bchain(Fact), !, fail. % Fail "not Fact" if you can prove it.• bchain(not _) :- !. % Otherwise just let it succeed.

• bchain(Fact):- % Fact is true if• rule(if Preconditions then Fact), % there's a rule concluding it• bchain(Preconditions). % and its Preconditions can be• % proved by backward chaining

• bchain(Fact):- % Fact is true if• user_says_its_true(Fact). % user says its true.

Page 105: Jack's Xtreme Prolog (5-8)

Interfaz y utilerías• % user_says_its_true(+Fact)• % True if there is some text to use to ask the user about it,• % and when you ask the user they say yes.

• user_says_its_true(Fact) :-• qtext(Fact, Question),• write_list(Question),• write("Please answer with either y. or n.: "),• read(Answer),• (Answer = y -> • assert(kbfact(user, Fact))• ; assert(kbfact(user, not Fact)), • fail• ).

• % Some utilities• member(H, [H|_]).• member(H, [_|T]) :- member(H, T).

• write_list([]) :- nl.• write_list([H|T]) :- write(H), write_list(T).

• reinit :- retractall(kbfact(user, _)).

Page 106: Jack's Xtreme Prolog (5-8)

Tarea

• Investigar:– Qué es ingenieria del conocimiento– Conjuntos difusos– Los criterios para usar backward o fordward

chaining, con ejemplos.

Page 107: Jack's Xtreme Prolog (5-8)

Tarea (2)

• Diseña e implementa las bases de conocimiento necesarias para el siguiente contexto:– Diagnóstico de problemas en una PC

• Consulta de un usuario al área de soporte técnico; el técnico experto hace preguntas sobre el estado de la computadora, el usuario contesta y se obtiene un diagnóstico

• Documenta las consideraciones y el diseño de la base de conocimiento

Page 108: Jack's Xtreme Prolog (5-8)

Referencias

• Visual Prolog http://www.visual-prolog.com/vip/vipinfo/freeware_version.htm

• Amzi! Prolog http://www.amzi.com/

• TDDB66 Expertsystem — metodik och verktyg http://www.ida.liu.se/~TDDB66/slides/Lecture1/index.htm