SlideShare una empresa de Scribd logo
1 de 10
Descargar para leer sin conexión
●
Prolog: Listas

Estructura básica

Unificación

Member

Append

Ejercicio

Árbol de seguimiento
Estructura básica

En prolog, una lista es una representación de un conjunto de
elementos.

La notación es la siguiente:
[manzana, pera, banana] lista vacia: [ ]

Se pueden utilizar cómo elementos de la lista cualquier tipo de
dato de prolog, incluyendo listas:
[[a,b,c],[d, e, f]]

También estructuras prolog:
[camino(tandil, bsas), camino(mardel, tandil),
camino(bsas,junin) ]
[vehiculo(ale, [bici, moto, auto]),
vehiculo(ariel,[bici, auto, helicoptero])]
Estructura básica

En su forma más básica, una lista se puede ver como un predicado
que tiene 2 partes:
lista(cabeza, cola)
en prolog:
[Cabeza | Cola]

Por ejemplo:
[Cabeza | Cola]=[1,2,3] [1] = [1|[ ]]
Cabeza=1,
Cola=[2,3]

Es una definición recursiva...
[1,2,3] = [1 | [ 2 , 3 ] ] = [1 | [ 2 | [3 ] ] ] = [1 | [ 2 | [3 | [ ] ] ] ]

Para probar:
?-X=[1,2,3],X = [1 | [ 2 , 3 ] ],
X = [1 | [ 2 | [3 ] ] ],X = [1 | [ 2 | [3 | [ ] ] ] ] .
Unificación

Ya vimos algunos ejemplos, pero hay mas:
[a,b,c]=[X,Y,Z]
X=a, Y=b, Z=c
[a,b,c] = [A, B, C|D]
A=a, B=b, C=c, D=[]
[a]=[A|B]
A=a, B=[]
[a,b,c,d,e] = [X,Y| Z]
X=a, Y=b, Z=[c,d,e]
[a,b,c] = [X,[Y|Z]]
No, espera que el segundo
elemento de la lista sea una lista.
[]=[X|Y] o [] = [X]
No!, la lista vacia no se puede dividir en cabeza y
cola
Es útil cuando definimos predicados de corte,
para estar seguros que una lista vacia no hace
match con una división cabeza-cola.
Por ej:
sumar([],R):-R=0. Mejor: sumar([],0).
sumar([ X | Y ],R) :- sumar(Y, R1), R is R1+X.
Member

Permite saber si un elemento pertenece a una lista:
member(1,[5,6,7,8,1,2,3]).
yes
member(1,[a,b,c])
no

Si el primer argumento es una variable, podemos listar los
elementos de una lista uno a uno, haciendo redo:
member(X,[a,b,c]).
yes, X=a;
yes, X=b;
yes, X=c;
No
Append

Permite unificar 2 listas en una:
append([1,2],[3,4],X)
X=[1,2,3,4]
o verificar que una lista es la unión de otras 2:
append([a,b],[c],[a,b,c])
yes

Es más útil con los argumentos sin instanciar:
append(X,[3,4],[1,2,3,4]).
Yes, X=[1,2]
append([1,2],Y,[1,2,3,4])
Yes, Y=[3,4]
Append

Permite conseguir todas las posibilidades de partir una lista en
2:
append(X,Y,[1,2,3,4])
X=[], Y=[1,2,3,4] ;
X=[1], Y=[2,3,4];
…
X=[1,2,3,4], Y=[]

En algunos casos nos sirve para agregar nuevos elementos a
una lista que vamos acarreando:
agregar(X, L, Lnueva):- append([X], L, Lnueva).
Que en realida también se podría hacer con unificación:
agregar(X, L, Lnueva):- Lnueva=[X|L].
pero como vimos, es lo mismo:
agregar(X, L, [X|L]).
Ejercicio

Tamaño de una lista:
size([a,b,c], N).
yes, N=3.
size([],0).
size([X|Y], N):-size(Y, N1), N is N1+1.

Se puede dejar sin instanciar el 1er argumento (Ejercicio 3.a).
Ejercicio

Rotar una lista:
Por ej:
?-rotar([1,2,3,4], L, 2).
L=[3,4,1,2].

Primer enfoque:
rotar(X,X,0).
rotar([X|Y], L, N):-N1 is N-1, append(Y,[X],Y1), rotar(Y1, L, N1).

Segundo enfoque:
rotar(L,R, N):-append(X, Y, L), size(X, N), append(Y, X, R).
Arbol de seguimiento
No
1) size([],0).
2) size([X|Y], N):-size(Y, N1), N is N1+1.
size([1,2,3], N)
Por 1)
size([2,3], N1), N' is N1 + 1
Por 2) X'=2, Y'=[3], N'=N''
Por 1)
No, no hace
matching el
vacio con la
lista
Por 2) X=1, Y=[2,3], N=N'
size([3], N1'), N'' is N1' + 1
Yes, N1''=0
Por 2) X''=3, Y''=[], N''=N'''
Por 1)
size([], N1''), N''' is N1'' + 1
Por 1)
No

Más contenido relacionado

Último

PIAR v 015. 2024 Plan Individual de ajustes razonables
PIAR v 015. 2024 Plan Individual de ajustes razonablesPIAR v 015. 2024 Plan Individual de ajustes razonables
PIAR v 015. 2024 Plan Individual de ajustes razonablesYanirisBarcelDelaHoz
 
Cuaderno de trabajo Matemática 3 tercer grado.pdf
Cuaderno de trabajo Matemática 3 tercer grado.pdfCuaderno de trabajo Matemática 3 tercer grado.pdf
Cuaderno de trabajo Matemática 3 tercer grado.pdfNancyLoaa
 
origen y desarrollo del ensayo literario
origen y desarrollo del ensayo literarioorigen y desarrollo del ensayo literario
origen y desarrollo del ensayo literarioELIASAURELIOCHAVEZCA1
 
Caja de herramientas de inteligencia artificial para la academia y la investi...
Caja de herramientas de inteligencia artificial para la academia y la investi...Caja de herramientas de inteligencia artificial para la academia y la investi...
Caja de herramientas de inteligencia artificial para la academia y la investi...Lourdes Feria
 
PLAN DE REFUERZO ESCOLAR primaria (1).docx
PLAN DE REFUERZO ESCOLAR primaria (1).docxPLAN DE REFUERZO ESCOLAR primaria (1).docx
PLAN DE REFUERZO ESCOLAR primaria (1).docxlupitavic
 
proyecto de mayo inicial 5 añitos aprender es bueno para tu niño
proyecto de mayo inicial 5 añitos aprender es bueno para tu niñoproyecto de mayo inicial 5 añitos aprender es bueno para tu niño
proyecto de mayo inicial 5 añitos aprender es bueno para tu niñotapirjackluis
 
Ley 21.545 - Circular Nº 586.pdf circular
Ley 21.545 - Circular Nº 586.pdf circularLey 21.545 - Circular Nº 586.pdf circular
Ley 21.545 - Circular Nº 586.pdf circularMooPandrea
 
plan de capacitacion docente AIP 2024 clllll.pdf
plan de capacitacion docente  AIP 2024          clllll.pdfplan de capacitacion docente  AIP 2024          clllll.pdf
plan de capacitacion docente AIP 2024 clllll.pdfenelcielosiempre
 
AFICHE EL MANIERISMO HISTORIA DE LA ARQUITECTURA II
AFICHE EL MANIERISMO HISTORIA DE LA ARQUITECTURA IIAFICHE EL MANIERISMO HISTORIA DE LA ARQUITECTURA II
AFICHE EL MANIERISMO HISTORIA DE LA ARQUITECTURA IIIsauraImbrondone
 
Estrategia de prompts, primeras ideas para su construcción
Estrategia de prompts, primeras ideas para su construcciónEstrategia de prompts, primeras ideas para su construcción
Estrategia de prompts, primeras ideas para su construcciónLourdes Feria
 
ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...
ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...
ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...JAVIER SOLIS NOYOLA
 
Dinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes dDinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes dstEphaniiie
 
plande accion dl aula de innovación pedagogica 2024.pdf
plande accion dl aula de innovación pedagogica 2024.pdfplande accion dl aula de innovación pedagogica 2024.pdf
plande accion dl aula de innovación pedagogica 2024.pdfenelcielosiempre
 
Registro Auxiliar - Primaria 2024 (1).pptx
Registro Auxiliar - Primaria  2024 (1).pptxRegistro Auxiliar - Primaria  2024 (1).pptx
Registro Auxiliar - Primaria 2024 (1).pptxFelicitasAsuncionDia
 
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICABIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICAÁngel Encinas
 
Estrategias de enseñanza-aprendizaje virtual.pptx
Estrategias de enseñanza-aprendizaje virtual.pptxEstrategias de enseñanza-aprendizaje virtual.pptx
Estrategias de enseñanza-aprendizaje virtual.pptxdkmeza
 
FORTI-MAYO 2024.pdf.CIENCIA,EDUCACION,CULTURA
FORTI-MAYO 2024.pdf.CIENCIA,EDUCACION,CULTURAFORTI-MAYO 2024.pdf.CIENCIA,EDUCACION,CULTURA
FORTI-MAYO 2024.pdf.CIENCIA,EDUCACION,CULTURAEl Fortí
 
La empresa sostenible: Principales Características, Barreras para su Avance y...
La empresa sostenible: Principales Características, Barreras para su Avance y...La empresa sostenible: Principales Características, Barreras para su Avance y...
La empresa sostenible: Principales Características, Barreras para su Avance y...JonathanCovena1
 
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdfCurso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdfFrancisco158360
 

Último (20)

PIAR v 015. 2024 Plan Individual de ajustes razonables
PIAR v 015. 2024 Plan Individual de ajustes razonablesPIAR v 015. 2024 Plan Individual de ajustes razonables
PIAR v 015. 2024 Plan Individual de ajustes razonables
 
Cuaderno de trabajo Matemática 3 tercer grado.pdf
Cuaderno de trabajo Matemática 3 tercer grado.pdfCuaderno de trabajo Matemática 3 tercer grado.pdf
Cuaderno de trabajo Matemática 3 tercer grado.pdf
 
origen y desarrollo del ensayo literario
origen y desarrollo del ensayo literarioorigen y desarrollo del ensayo literario
origen y desarrollo del ensayo literario
 
Caja de herramientas de inteligencia artificial para la academia y la investi...
Caja de herramientas de inteligencia artificial para la academia y la investi...Caja de herramientas de inteligencia artificial para la academia y la investi...
Caja de herramientas de inteligencia artificial para la academia y la investi...
 
PLAN DE REFUERZO ESCOLAR primaria (1).docx
PLAN DE REFUERZO ESCOLAR primaria (1).docxPLAN DE REFUERZO ESCOLAR primaria (1).docx
PLAN DE REFUERZO ESCOLAR primaria (1).docx
 
proyecto de mayo inicial 5 añitos aprender es bueno para tu niño
proyecto de mayo inicial 5 añitos aprender es bueno para tu niñoproyecto de mayo inicial 5 añitos aprender es bueno para tu niño
proyecto de mayo inicial 5 añitos aprender es bueno para tu niño
 
Ley 21.545 - Circular Nº 586.pdf circular
Ley 21.545 - Circular Nº 586.pdf circularLey 21.545 - Circular Nº 586.pdf circular
Ley 21.545 - Circular Nº 586.pdf circular
 
plan de capacitacion docente AIP 2024 clllll.pdf
plan de capacitacion docente  AIP 2024          clllll.pdfplan de capacitacion docente  AIP 2024          clllll.pdf
plan de capacitacion docente AIP 2024 clllll.pdf
 
AFICHE EL MANIERISMO HISTORIA DE LA ARQUITECTURA II
AFICHE EL MANIERISMO HISTORIA DE LA ARQUITECTURA IIAFICHE EL MANIERISMO HISTORIA DE LA ARQUITECTURA II
AFICHE EL MANIERISMO HISTORIA DE LA ARQUITECTURA II
 
Estrategia de prompts, primeras ideas para su construcción
Estrategia de prompts, primeras ideas para su construcciónEstrategia de prompts, primeras ideas para su construcción
Estrategia de prompts, primeras ideas para su construcción
 
ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...
ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...
ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...
 
Dinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes dDinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes d
 
plande accion dl aula de innovación pedagogica 2024.pdf
plande accion dl aula de innovación pedagogica 2024.pdfplande accion dl aula de innovación pedagogica 2024.pdf
plande accion dl aula de innovación pedagogica 2024.pdf
 
Fe contra todo pronóstico. La fe es confianza.
Fe contra todo pronóstico. La fe es confianza.Fe contra todo pronóstico. La fe es confianza.
Fe contra todo pronóstico. La fe es confianza.
 
Registro Auxiliar - Primaria 2024 (1).pptx
Registro Auxiliar - Primaria  2024 (1).pptxRegistro Auxiliar - Primaria  2024 (1).pptx
Registro Auxiliar - Primaria 2024 (1).pptx
 
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICABIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
 
Estrategias de enseñanza-aprendizaje virtual.pptx
Estrategias de enseñanza-aprendizaje virtual.pptxEstrategias de enseñanza-aprendizaje virtual.pptx
Estrategias de enseñanza-aprendizaje virtual.pptx
 
FORTI-MAYO 2024.pdf.CIENCIA,EDUCACION,CULTURA
FORTI-MAYO 2024.pdf.CIENCIA,EDUCACION,CULTURAFORTI-MAYO 2024.pdf.CIENCIA,EDUCACION,CULTURA
FORTI-MAYO 2024.pdf.CIENCIA,EDUCACION,CULTURA
 
La empresa sostenible: Principales Características, Barreras para su Avance y...
La empresa sostenible: Principales Características, Barreras para su Avance y...La empresa sostenible: Principales Características, Barreras para su Avance y...
La empresa sostenible: Principales Características, Barreras para su Avance y...
 
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdfCurso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdf
 

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

clase3.pdf

  • 2. Estructura básica  En prolog, una lista es una representación de un conjunto de elementos.  La notación es la siguiente: [manzana, pera, banana] lista vacia: [ ]  Se pueden utilizar cómo elementos de la lista cualquier tipo de dato de prolog, incluyendo listas: [[a,b,c],[d, e, f]]  También estructuras prolog: [camino(tandil, bsas), camino(mardel, tandil), camino(bsas,junin) ] [vehiculo(ale, [bici, moto, auto]), vehiculo(ariel,[bici, auto, helicoptero])]
  • 3. Estructura básica  En su forma más básica, una lista se puede ver como un predicado que tiene 2 partes: lista(cabeza, cola) en prolog: [Cabeza | Cola]  Por ejemplo: [Cabeza | Cola]=[1,2,3] [1] = [1|[ ]] Cabeza=1, Cola=[2,3]  Es una definición recursiva... [1,2,3] = [1 | [ 2 , 3 ] ] = [1 | [ 2 | [3 ] ] ] = [1 | [ 2 | [3 | [ ] ] ] ]  Para probar: ?-X=[1,2,3],X = [1 | [ 2 , 3 ] ], X = [1 | [ 2 | [3 ] ] ],X = [1 | [ 2 | [3 | [ ] ] ] ] .
  • 4. Unificación  Ya vimos algunos ejemplos, pero hay mas: [a,b,c]=[X,Y,Z] X=a, Y=b, Z=c [a,b,c] = [A, B, C|D] A=a, B=b, C=c, D=[] [a]=[A|B] A=a, B=[] [a,b,c,d,e] = [X,Y| Z] X=a, Y=b, Z=[c,d,e] [a,b,c] = [X,[Y|Z]] No, espera que el segundo elemento de la lista sea una lista. []=[X|Y] o [] = [X] No!, la lista vacia no se puede dividir en cabeza y cola Es útil cuando definimos predicados de corte, para estar seguros que una lista vacia no hace match con una división cabeza-cola. Por ej: sumar([],R):-R=0. Mejor: sumar([],0). sumar([ X | Y ],R) :- sumar(Y, R1), R is R1+X.
  • 5. Member  Permite saber si un elemento pertenece a una lista: member(1,[5,6,7,8,1,2,3]). yes member(1,[a,b,c]) no  Si el primer argumento es una variable, podemos listar los elementos de una lista uno a uno, haciendo redo: member(X,[a,b,c]). yes, X=a; yes, X=b; yes, X=c; No
  • 6. Append  Permite unificar 2 listas en una: append([1,2],[3,4],X) X=[1,2,3,4] o verificar que una lista es la unión de otras 2: append([a,b],[c],[a,b,c]) yes  Es más útil con los argumentos sin instanciar: append(X,[3,4],[1,2,3,4]). Yes, X=[1,2] append([1,2],Y,[1,2,3,4]) Yes, Y=[3,4]
  • 7. Append  Permite conseguir todas las posibilidades de partir una lista en 2: append(X,Y,[1,2,3,4]) X=[], Y=[1,2,3,4] ; X=[1], Y=[2,3,4]; … X=[1,2,3,4], Y=[]  En algunos casos nos sirve para agregar nuevos elementos a una lista que vamos acarreando: agregar(X, L, Lnueva):- append([X], L, Lnueva). Que en realida también se podría hacer con unificación: agregar(X, L, Lnueva):- Lnueva=[X|L]. pero como vimos, es lo mismo: agregar(X, L, [X|L]).
  • 8. Ejercicio  Tamaño de una lista: size([a,b,c], N). yes, N=3. size([],0). size([X|Y], N):-size(Y, N1), N is N1+1.  Se puede dejar sin instanciar el 1er argumento (Ejercicio 3.a).
  • 9. Ejercicio  Rotar una lista: Por ej: ?-rotar([1,2,3,4], L, 2). L=[3,4,1,2].  Primer enfoque: rotar(X,X,0). rotar([X|Y], L, N):-N1 is N-1, append(Y,[X],Y1), rotar(Y1, L, N1).  Segundo enfoque: rotar(L,R, N):-append(X, Y, L), size(X, N), append(Y, X, R).
  • 10. Arbol de seguimiento No 1) size([],0). 2) size([X|Y], N):-size(Y, N1), N is N1+1. size([1,2,3], N) Por 1) size([2,3], N1), N' is N1 + 1 Por 2) X'=2, Y'=[3], N'=N'' Por 1) No, no hace matching el vacio con la lista Por 2) X=1, Y=[2,3], N=N' size([3], N1'), N'' is N1' + 1 Yes, N1''=0 Por 2) X''=3, Y''=[], N''=N''' Por 1) size([], N1''), N''' is N1'' + 1 Por 1) No