SlideShare a Scribd company logo
1 of 32
Download to read offline
Lecture 01 :

A Gentle Introduction to
Reflection
LSINF 2335
Programming Paradigms
Prof. Kim Mens
UCL / EPL / INGI
Disclaimer: any pictures used in this presentation
remain with the copyright of their original owner and
were included here for didactical purposes only. In case
of any suspected violation of copyright please contact
me so that I can remove or replace those pictures.
Motivation
LSINF 2335
Prof. Kim Mens
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic. Programming Paradigms:
Theory, Practice and Applications
■ Safir-Whorf Hypothesis (linguistics)
– A particular language's nature influences the habitual
thought of its speakers: different language patterns
yield different patterns of thought.
■ Consequence:
– language influences the thoughts of people who use it
– language determines how we see and think about the world
– the limits of one's language become the limits of one's world
3
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic. Programming Paradigms:
Theory, Practice and Applications
■ Safir-Whorf Hypothesis applied to programming
– The programming language used determines how we see and
think about the solution.
■ Is a good programmer as efficient regardless of the
language used?
– Probably not; neither is the program...
■ A programming language is a problem-solving tool
– Choose right programming language to solve your problem
– A good language still doesn’t make a good programmer...
• ... but it can make a bad programmer perform well
• And make a good programmer perform better
4
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic. Programming Paradigms:
Theory, Practice and Applications
5
“When you only have a hammer, everything looks like a nail”
■ Do you only know 1 or 2 languages / paradigms?
– Is that really the situation you want to be in when
developing ?
– Aren’t we supposed to be the computer science experts?
■ This course focusses on advanced programming
languages, paradigms and techniques
– Selected theme: reflection, metaprogramming

and a bit of context-oriented programming.
Reflection
LSINF 2335
Prof. Kim Mens
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflection (language)
■ Meaning
– one of the meanings of reflection (in English) is
“introspection” : contemplation of one-self
– in other words, reflection is the ability of a thing to talk about
itself
■ Reflection in natural language
– “This sentence contains 37 characters.”
– “This sentence contains 27 letters.”
■ Reflection can easily introduce paradoxes
– “This sentence is false.”
• Suppose true. Then claim is correct. So false. Contradiction.
• Suppose false. Then claim is wrong. So true. Contradiction.
7
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflection (art)
8
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
9
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflection (computing)
■ In computer science, (computational) reflection is the
ability of a program to examine and control its own
implementation
■ Reflective programming
– is the programming paradigm driven by reflection
– is a special case of metaprogramming*
■ Computational reflection is good for (a.o.)
– extending a language / language design
– building programming environments
– advanced software development tools
– building knowledge and learning systems
– self-modifying / self-optimising applications
10
* see later
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflection (computing)
■ Reflection is a pretty advanced feature
– requires strong grasp of the fundamentals of the language
– allows to solve problems elegantly, that were
• previously handled on an ad-hoc basis
• or hard / impossible to achieve
■ Be careful not to introduce paradoxes
– It is possible to write programs that modify themselves while
being executed
– If you’re not careful this can lead to weird situations
– Here’s an example you all know:
• Modifying a data-structure while iterating over it.
• And that’s not even reflection...
11
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective languages
■ Many programmers (and some programming languages) do not
fully recognise the importance of reflection
– for example, debugging a program by manually adding
debugging statements all over
■ Some languages provide some types of reflection
– for debugging or error handling only
– or only introspection but no real modification of existing
programs
■ Aspect-oriented languages take it a step further
– but still limited by the set of constructs they offer
12
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective languages
■ Fully reflective languages offer the full power of
reflection
– allow to reason about and modify nearly any aspect of a running
program
■ Today, many programming languages offer interesting
reflective capabilities
– common in high-level virtual machine programming languages like
Smalltalk
• note: Java is not fully reflective (mainly introspection)
– less common in lower-level programming languages like C
13
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective languages
■ Have you ever thought of...
– writing a program to generate a visitor class, given a class
hierarchy ?
– adding methods on a class while your code is running ?
– finding out all the instances of a particular class at runtime, or
– all messages understood by an object ?
– adding new keywords to your language ?
■ In a fully reflective language like Smalltalk you can do
all that...
■ ... and more.
14
Metaprogramming
LSINF 2335
Prof. Kim Mens
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflection (computing)
■ In computer science, (computational) reflection is the
ability of a program to examine and control its own
implementation
■ Reflective programming
– is the programming paradigm driven by reflection
– is a special case of metaprogramming
■ Computational reflection is good for (a.o.)
– extending a language / language design
– building programming environments
– advanced software development tools
– building knowledge and learning systems
– self-modifying / self-optimising applications
16
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Meta (language)
■ In Greek
– The preposition µετά means "after", "beside" or "with"
■ In English
– the prefix meta- means “about” (its own category)
– for example, metadata are data about data
• (who has produced it, when, what format are the data in, ...)
– Douglas Hofstadter popularised the meaning of the term
• For example, “going meta”
– rethorical trick to take a debate or analysis to a higher
abstraction level
– “This discussion isn’t really going anywhere.”
• His books “Gödel, Escher, Bach” and “Metamagical Themas” are
a must-read (for any self-reflecting computer scientist)
17
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Meta (computing)
■ In computer science
– metaprogramming is the writing of computer programs that
write or manipulate other programs as their data
– reflective programming is a case of metaprogramming
• where a program is its own metaprogram
• i.e., when a program manipulates itself
■ Well-known examples of metaprogramming
– a compiler
– an interpreter
– a code analysis tool
– a code generator
– ... 18
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Quine (the philosopher)
■ Willard Van Orman Quine (1908–2000)
■ Philosopher who made an extensive study of indirect
self-reference
■ Quine’s paradox
– ‘Yields falsehood when preceded by its quotation’
– Can you see the paradox?
19
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Quine (the philosopher)
■ Willard Van Orman Quine (1908–2000)
■ Philosopher who made an extensive study of indirect
self-reference
■ Quine’s paradox
– ‘Yields falsehood when preceded by its quotation’
– “ ‘Yields falsehood when preceded by its quotation’ yields
falsehood when preceded by its quotation ”
• Suppose true. Then sentence states falsehood. Contradiction.
• Suppose false. Then sentence is wrong. So it does yield falsehood.
Therefore sentence must be true. Contradiction.
20
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Quine (programs)
■ In computing a quine is a program that produces its
complete source code as its only output
■ A quine is a metaprogram
– can be a reflective program
■ Some restrictions
– program cannot take input
– empty programs are not allowed
• The empty quine once won the “worst abuse of the rules” price in the
Obfuscated C contest
■ The Quine page
– http://www.nyx.net/~gthompso/quine.htm
– http://en.wikipedia.org/wiki/Quine_(computing)
21
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Quine (Javascript)
■ Here’s a quine in Javascript
function a() { document.write (a + "na();"); }
a();
■ almost trivial because Javascript gives you access to a
function’s source code
22
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Bootstrapping
■ An allusion to lift yourself up by your own bootstraps
■ Bootstrapping means using a special process to perform a task that one
would be unable to do in general
– for example, writing a compiler in terms of itself
– start with a simple compiler, compile a more complex version in that
one
■ When write a Quine
– The program has a code part and a data part
– The data part represents the entire code
– But the code contains the data part
– Seems like a paradox: how can the data part contain itself?
– Bootstrapping needed:
• put special character in data part
• replace that character by the data part itself
23
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Quine (C) 1/6
/* A simple quine (self-printing program), in standard C. */
/* Note: in designing this quine, we have tried to make the code clear
* and readable, not concise and obscure as many quines are, so that
* the general principle can be made clear at the expense of length.
* In a nutshell: use the same data structure (called "progdata"
* below) to output the program code (which it represents) and its own
* textual representation. */
#include <stdio.h>
void quote(const char *s)
/* This function takes a character string s and prints the
* textual representation of s as it might appear formatted
* in C code. */
{
int i;
printf(" "");
...
24
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Quine (C) 2/6
for (i=0; s[i]; ++i) {
/* Certain characters are quoted. */
if (s[i] == '')
printf("");
else if (s[i] == '"')
printf(""");
else if (s[i] == 'n')
printf("n");
/* Others are just printed as such. */
else
printf("%c", s[i]);
/* Also insert occasional line breaks. */
if (i % 48 == 47)
printf(""n "");
}
printf(""");
}
...
25
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Quine (C) 3/6
/* What follows is a string representation of the program code,
* from beginning to end (formatted as per the quote() function
* above), except that the string _itself_ is coded as two
* consecutive '@' characters. */
const char progdata[] =
"/* A simple quine (self-printing program), in st"
"andard C. */nn/* Note: in designing this quine, "
"we have tried to make the code clearn * and read"
"able, not concise and obscure as many quines are"
", so thatn * the general principle can be made c"
"lear at the expense of length.n * In a nutshell:"
" use the same data structure (called "progdata"n"
" * below) to output the program code (which it r"
"epresents) and its ownn * textual representation"
". */nn#include <stdio.h>nnvoid quote(const char "
"*s)n /* This function takes a character stri"
"ng s and prints then * textual representati"
"on of s as it might appear formattedn * in "
"C code. */n{n int i;nn printf(" "");n
...
26
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Quine (C) 4/6
" for (i=0; s[i]; ++i) {n /* Certain cha"
"racters are quoted. */n if (s[i] == '')"
"n printf("");n else if (s["
"i] == '"')n printf(""");n e"
"lse if (s[i] == 'n')n printf("n");"
"n /* Others are just printed as such. */n"
" elsen printf("%c", s[i]);n "
" /* Also insert occasional line breaks. */n "
" if (i % 48 == 47)n printf("""
"n "");n }n printf(""");n}nn/* What fo"
"llows is a string representation of the program "
"code,n * from beginning to end (formatted as per"
" the quote() functionn * above), except that the"
" string _itself_ is coded as twon * consecutive "
"'@' characters. */nconst char progdata[] =n@@;nn"
"int main(void)n /* The program itself... */n"
"{n int i;nn /* Print the program code, cha"
"racter by character. */n for (i=0; progdata[i"
"]; ++i) {n if (progdata[i] == '@' && prog"
... 27
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Quine (C) 5/6
"data[i+1] == '@')n /* We encounter tw"
"o '@' signs, so we must print the quotedn "
" * form of the program code. */n {n "
" quote(progdata); /* Quote all. */n"
" i++; /* Skip second '"
"@'. */n } elsen printf("%c", p"
"rogdata[i]); /* Print character. */n }n r"
"eturn 0;n}n";
int main(void)
/* The program itself... */
{
int i;
/* Print the program code, character by character. */
for (i=0; progdata[i]; ++i) {
if (progdata[i] == '@' && progdata[i+1] == '@')
/* We encounter two '@' signs, so we must print the quoted
* form of the program code. */
...
28
look for two consecutive
@ characters and replace
them by program string
itself
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Quine (C) 6/6
{
quote(progdata); /* Quote all. */
i++; /* Skip second '@'. */
} else
printf("%c", progdata[i]); /* Print character. */
}
return 0;
}
■ Reflective questions (pun intended)
– Is this a metaprogram?
– Is it a reflective program?
– Is it self-modifying?
29
Wrap up
LSINF 2335
Prof. Kim Mens
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Things to remember
■ Meta (programming)
■ (Computational) Reflection
■ Bootstrapping
31
LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic. Comprehension exercises
■ Do you believe the Safir-Whorf hypothesis applies to
programming ?
■ Write a paradoxical reflective sentence and explain why it is
paradoxical
■ Is the following “definition” reflective?
– recursive: adjective, see recursive
■ Explain reflection, metaprogramming and bootstrapping in your own
words.
■ Explain the word “meta” without going meta.
■ Write a quine in a programming language of your choice.
■ Can you write one that makes use of reflection?
■ Are you programming reflectively when you use the keyword “this”
in Java?
■ Read the book : “Gödel, Escher, Bach”.
32

More Related Content

What's hot

Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
Ganesh Samarthyam
 
9781111530532 ppt ch05
9781111530532 ppt ch059781111530532 ppt ch05
9781111530532 ppt ch05
Terry Yoast
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
Terry Yoast
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
rahulsahay19
 
9781111530532 ppt ch07
9781111530532 ppt ch079781111530532 ppt ch07
9781111530532 ppt ch07
Terry Yoast
 
9781111530532 ppt ch03
9781111530532 ppt ch039781111530532 ppt ch03
9781111530532 ppt ch03
Terry Yoast
 
9781439035665 ppt ch05
9781439035665 ppt ch059781439035665 ppt ch05
9781439035665 ppt ch05
Terry Yoast
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
Adan Hubahib
 

What's hot (20)

Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
9781111530532 ppt ch05
9781111530532 ppt ch059781111530532 ppt ch05
9781111530532 ppt ch05
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
 
Procedural programming
Procedural programmingProcedural programming
Procedural programming
 
9781111530532 ppt ch07
9781111530532 ppt ch079781111530532 ppt ch07
9781111530532 ppt ch07
 
9781111530532 ppt ch03
9781111530532 ppt ch039781111530532 ppt ch03
9781111530532 ppt ch03
 
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
 
ASE02 DMP.ppt
ASE02 DMP.pptASE02 DMP.ppt
ASE02 DMP.ppt
 
OOP in Java
OOP in JavaOOP in Java
OOP in Java
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
9781439035665 ppt ch05
9781439035665 ppt ch059781439035665 ppt ch05
9781439035665 ppt ch05
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
 
Short notes of oop with java
Short notes of oop with javaShort notes of oop with java
Short notes of oop with java
 
01. Introduction to Programming
01. Introduction to Programming01. Introduction to Programming
01. Introduction to Programming
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 

Similar to A gentle introduction to reflection

Agile software development
Agile software developmentAgile software development
Agile software development
Hemangi Talele
 

Similar to A gentle introduction to reflection (20)

Paradigms
ParadigmsParadigms
Paradigms
 
Introduction to computing and Programming (ppt)
Introduction to computing and Programming (ppt)Introduction to computing and Programming (ppt)
Introduction to computing and Programming (ppt)
 
Plc part 1
Plc part 1Plc part 1
Plc part 1
 
Are High Level Programming Languages for Multicore and Safety Critical Conver...
Are High Level Programming Languages for Multicore and Safety Critical Conver...Are High Level Programming Languages for Multicore and Safety Critical Conver...
Are High Level Programming Languages for Multicore and Safety Critical Conver...
 
Imperative programming
Imperative programmingImperative programming
Imperative programming
 
CS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionCS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: Introduction
 
Programming languages and concepts by vivek parihar
Programming languages and concepts by vivek pariharProgramming languages and concepts by vivek parihar
Programming languages and concepts by vivek parihar
 
DMA113 Chap1
DMA113 Chap1DMA113 Chap1
DMA113 Chap1
 
Themes for graduation projects 2010
Themes for graduation projects   2010Themes for graduation projects   2010
Themes for graduation projects 2010
 
Lec 1 25_jul13
Lec 1 25_jul13Lec 1 25_jul13
Lec 1 25_jul13
 
Evolution of Programming Languages.pdf
Evolution of Programming Languages.pdfEvolution of Programming Languages.pdf
Evolution of Programming Languages.pdf
 
Evolution of Programming Languages.pdf
Evolution of Programming Languages.pdfEvolution of Programming Languages.pdf
Evolution of Programming Languages.pdf
 
Attention-based Models (DLAI D8L 2017 UPC Deep Learning for Artificial Intell...
Attention-based Models (DLAI D8L 2017 UPC Deep Learning for Artificial Intell...Attention-based Models (DLAI D8L 2017 UPC Deep Learning for Artificial Intell...
Attention-based Models (DLAI D8L 2017 UPC Deep Learning for Artificial Intell...
 
PL Lecture 01 - preliminaries
PL Lecture 01 - preliminariesPL Lecture 01 - preliminaries
PL Lecture 01 - preliminaries
 
Agile software development
Agile software developmentAgile software development
Agile software development
 
APP_All Five Unit PPT_NOTES.pptx
APP_All Five Unit PPT_NOTES.pptxAPP_All Five Unit PPT_NOTES.pptx
APP_All Five Unit PPT_NOTES.pptx
 
5-CEN6016-Chapter1.ppt
5-CEN6016-Chapter1.ppt5-CEN6016-Chapter1.ppt
5-CEN6016-Chapter1.ppt
 
Антон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLabАнтон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLab
 
Agile Software Development.ppt
Agile Software Development.pptAgile Software Development.ppt
Agile Software Development.ppt
 
On being a professional software developer
On being a professional software developerOn being a professional software developer
On being a professional software developer
 

More from kim.mens

More from kim.mens (20)

Software Maintenance and Evolution
Software Maintenance and EvolutionSoftware Maintenance and Evolution
Software Maintenance and Evolution
 
Context-Oriented Programming
Context-Oriented ProgrammingContext-Oriented Programming
Context-Oriented Programming
 
Software Reuse and Object-Oriented Programming
Software Reuse and Object-Oriented ProgrammingSoftware Reuse and Object-Oriented Programming
Software Reuse and Object-Oriented Programming
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smells
 
Object-Oriented Design Heuristics
Object-Oriented Design HeuristicsObject-Oriented Design Heuristics
Object-Oriented Design Heuristics
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Domain Modelling
Domain ModellingDomain Modelling
Domain Modelling
 
Object-Oriented Application Frameworks
Object-Oriented Application FrameworksObject-Oriented Application Frameworks
Object-Oriented Application Frameworks
 
Towards a Context-Oriented Software Implementation Framework
Towards a Context-Oriented Software Implementation FrameworkTowards a Context-Oriented Software Implementation Framework
Towards a Context-Oriented Software Implementation Framework
 
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
Towards a Taxonomy of Context-Aware Software Variabilty ApproachesTowards a Taxonomy of Context-Aware Software Variabilty Approaches
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
 
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Breaking the Walls: A Unified Vision on Context-Oriented Software EngineeringBreaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
 
Context-oriented programming
Context-oriented programmingContext-oriented programming
Context-oriented programming
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
Introduction to Smalltalk
Introduction to SmalltalkIntroduction to Smalltalk
Introduction to Smalltalk
 
Managing the Evolution of Information Systems with Intensional Views and Rela...
Managing the Evolution of Information Systems with Intensional Views and Rela...Managing the Evolution of Information Systems with Intensional Views and Rela...
Managing the Evolution of Information Systems with Intensional Views and Rela...
 
Usage contracts (presented at SATToSE 2014 in L'Aquila, Italy)
Usage contracts (presented at SATToSE 2014 in L'Aquila, Italy)Usage contracts (presented at SATToSE 2014 in L'Aquila, Italy)
Usage contracts (presented at SATToSE 2014 in L'Aquila, Italy)
 
Usage contracts in a nutshell
Usage contracts in a nutshellUsage contracts in a nutshell
Usage contracts in a nutshell
 
INGI2252 Software Measures & Maintenance
INGI2252 Software Measures & MaintenanceINGI2252 Software Measures & Maintenance
INGI2252 Software Measures & Maintenance
 

Recently uploaded

Bacterial Identification and Classifications
Bacterial Identification and ClassificationsBacterial Identification and Classifications
Bacterial Identification and Classifications
Areesha Ahmad
 
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 bAsymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Sérgio Sacani
 
Chemical Tests; flame test, positive and negative ions test Edexcel Internati...
Chemical Tests; flame test, positive and negative ions test Edexcel Internati...Chemical Tests; flame test, positive and negative ions test Edexcel Internati...
Chemical Tests; flame test, positive and negative ions test Edexcel Internati...
ssuser79fe74
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
PirithiRaju
 
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
PirithiRaju
 
Seismic Method Estimate velocity from seismic data.pptx
Seismic Method Estimate velocity from seismic  data.pptxSeismic Method Estimate velocity from seismic  data.pptx
Seismic Method Estimate velocity from seismic data.pptx
AlMamun560346
 

Recently uploaded (20)

Kochi ❤CALL GIRL 84099*07087 ❤CALL GIRLS IN Kochi ESCORT SERVICE❤CALL GIRL
Kochi ❤CALL GIRL 84099*07087 ❤CALL GIRLS IN Kochi ESCORT SERVICE❤CALL GIRLKochi ❤CALL GIRL 84099*07087 ❤CALL GIRLS IN Kochi ESCORT SERVICE❤CALL GIRL
Kochi ❤CALL GIRL 84099*07087 ❤CALL GIRLS IN Kochi ESCORT SERVICE❤CALL GIRL
 
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
 
Bacterial Identification and Classifications
Bacterial Identification and ClassificationsBacterial Identification and Classifications
Bacterial Identification and Classifications
 
Creating and Analyzing Definitive Screening Designs
Creating and Analyzing Definitive Screening DesignsCreating and Analyzing Definitive Screening Designs
Creating and Analyzing Definitive Screening Designs
 
SAMASTIPUR CALL GIRL 7857803690 LOW PRICE ESCORT SERVICE
SAMASTIPUR CALL GIRL 7857803690  LOW PRICE  ESCORT SERVICESAMASTIPUR CALL GIRL 7857803690  LOW PRICE  ESCORT SERVICE
SAMASTIPUR CALL GIRL 7857803690 LOW PRICE ESCORT SERVICE
 
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
 
Botany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdfBotany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdf
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
 
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 bAsymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
 
Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )
 
Green chemistry and Sustainable development.pptx
Green chemistry  and Sustainable development.pptxGreen chemistry  and Sustainable development.pptx
Green chemistry and Sustainable development.pptx
 
Chemical Tests; flame test, positive and negative ions test Edexcel Internati...
Chemical Tests; flame test, positive and negative ions test Edexcel Internati...Chemical Tests; flame test, positive and negative ions test Edexcel Internati...
Chemical Tests; flame test, positive and negative ions test Edexcel Internati...
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
 
Isotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoIsotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on Io
 
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
 
Seismic Method Estimate velocity from seismic data.pptx
Seismic Method Estimate velocity from seismic  data.pptxSeismic Method Estimate velocity from seismic  data.pptx
Seismic Method Estimate velocity from seismic data.pptx
 
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 60009654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
 
COST ESTIMATION FOR A RESEARCH PROJECT.pptx
COST ESTIMATION FOR A RESEARCH PROJECT.pptxCOST ESTIMATION FOR A RESEARCH PROJECT.pptx
COST ESTIMATION FOR A RESEARCH PROJECT.pptx
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptx
 

A gentle introduction to reflection

  • 1. Lecture 01 :
 A Gentle Introduction to Reflection LSINF 2335 Programming Paradigms Prof. Kim Mens UCL / EPL / INGI Disclaimer: any pictures used in this presentation remain with the copyright of their original owner and were included here for didactical purposes only. In case of any suspected violation of copyright please contact me so that I can remove or replace those pictures.
  • 3. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Programming Paradigms: Theory, Practice and Applications ■ Safir-Whorf Hypothesis (linguistics) – A particular language's nature influences the habitual thought of its speakers: different language patterns yield different patterns of thought. ■ Consequence: – language influences the thoughts of people who use it – language determines how we see and think about the world – the limits of one's language become the limits of one's world 3
  • 4. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Programming Paradigms: Theory, Practice and Applications ■ Safir-Whorf Hypothesis applied to programming – The programming language used determines how we see and think about the solution. ■ Is a good programmer as efficient regardless of the language used? – Probably not; neither is the program... ■ A programming language is a problem-solving tool – Choose right programming language to solve your problem – A good language still doesn’t make a good programmer... • ... but it can make a bad programmer perform well • And make a good programmer perform better 4
  • 5. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Programming Paradigms: Theory, Practice and Applications 5 “When you only have a hammer, everything looks like a nail” ■ Do you only know 1 or 2 languages / paradigms? – Is that really the situation you want to be in when developing ? – Aren’t we supposed to be the computer science experts? ■ This course focusses on advanced programming languages, paradigms and techniques – Selected theme: reflection, metaprogramming
 and a bit of context-oriented programming.
  • 7. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflection (language) ■ Meaning – one of the meanings of reflection (in English) is “introspection” : contemplation of one-self – in other words, reflection is the ability of a thing to talk about itself ■ Reflection in natural language – “This sentence contains 37 characters.” – “This sentence contains 27 letters.” ■ Reflection can easily introduce paradoxes – “This sentence is false.” • Suppose true. Then claim is correct. So false. Contradiction. • Suppose false. Then claim is wrong. So true. Contradiction. 7
  • 10. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflection (computing) ■ In computer science, (computational) reflection is the ability of a program to examine and control its own implementation ■ Reflective programming – is the programming paradigm driven by reflection – is a special case of metaprogramming* ■ Computational reflection is good for (a.o.) – extending a language / language design – building programming environments – advanced software development tools – building knowledge and learning systems – self-modifying / self-optimising applications 10 * see later
  • 11. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflection (computing) ■ Reflection is a pretty advanced feature – requires strong grasp of the fundamentals of the language – allows to solve problems elegantly, that were • previously handled on an ad-hoc basis • or hard / impossible to achieve ■ Be careful not to introduce paradoxes – It is possible to write programs that modify themselves while being executed – If you’re not careful this can lead to weird situations – Here’s an example you all know: • Modifying a data-structure while iterating over it. • And that’s not even reflection... 11
  • 12. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective languages ■ Many programmers (and some programming languages) do not fully recognise the importance of reflection – for example, debugging a program by manually adding debugging statements all over ■ Some languages provide some types of reflection – for debugging or error handling only – or only introspection but no real modification of existing programs ■ Aspect-oriented languages take it a step further – but still limited by the set of constructs they offer 12
  • 13. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective languages ■ Fully reflective languages offer the full power of reflection – allow to reason about and modify nearly any aspect of a running program ■ Today, many programming languages offer interesting reflective capabilities – common in high-level virtual machine programming languages like Smalltalk • note: Java is not fully reflective (mainly introspection) – less common in lower-level programming languages like C 13
  • 14. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective languages ■ Have you ever thought of... – writing a program to generate a visitor class, given a class hierarchy ? – adding methods on a class while your code is running ? – finding out all the instances of a particular class at runtime, or – all messages understood by an object ? – adding new keywords to your language ? ■ In a fully reflective language like Smalltalk you can do all that... ■ ... and more. 14
  • 16. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflection (computing) ■ In computer science, (computational) reflection is the ability of a program to examine and control its own implementation ■ Reflective programming – is the programming paradigm driven by reflection – is a special case of metaprogramming ■ Computational reflection is good for (a.o.) – extending a language / language design – building programming environments – advanced software development tools – building knowledge and learning systems – self-modifying / self-optimising applications 16
  • 17. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Meta (language) ■ In Greek – The preposition µετά means "after", "beside" or "with" ■ In English – the prefix meta- means “about” (its own category) – for example, metadata are data about data • (who has produced it, when, what format are the data in, ...) – Douglas Hofstadter popularised the meaning of the term • For example, “going meta” – rethorical trick to take a debate or analysis to a higher abstraction level – “This discussion isn’t really going anywhere.” • His books “Gödel, Escher, Bach” and “Metamagical Themas” are a must-read (for any self-reflecting computer scientist) 17
  • 18. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Meta (computing) ■ In computer science – metaprogramming is the writing of computer programs that write or manipulate other programs as their data – reflective programming is a case of metaprogramming • where a program is its own metaprogram • i.e., when a program manipulates itself ■ Well-known examples of metaprogramming – a compiler – an interpreter – a code analysis tool – a code generator – ... 18
  • 19. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Quine (the philosopher) ■ Willard Van Orman Quine (1908–2000) ■ Philosopher who made an extensive study of indirect self-reference ■ Quine’s paradox – ‘Yields falsehood when preceded by its quotation’ – Can you see the paradox? 19
  • 20. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Quine (the philosopher) ■ Willard Van Orman Quine (1908–2000) ■ Philosopher who made an extensive study of indirect self-reference ■ Quine’s paradox – ‘Yields falsehood when preceded by its quotation’ – “ ‘Yields falsehood when preceded by its quotation’ yields falsehood when preceded by its quotation ” • Suppose true. Then sentence states falsehood. Contradiction. • Suppose false. Then sentence is wrong. So it does yield falsehood. Therefore sentence must be true. Contradiction. 20
  • 21. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Quine (programs) ■ In computing a quine is a program that produces its complete source code as its only output ■ A quine is a metaprogram – can be a reflective program ■ Some restrictions – program cannot take input – empty programs are not allowed • The empty quine once won the “worst abuse of the rules” price in the Obfuscated C contest ■ The Quine page – http://www.nyx.net/~gthompso/quine.htm – http://en.wikipedia.org/wiki/Quine_(computing) 21
  • 22. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Quine (Javascript) ■ Here’s a quine in Javascript function a() { document.write (a + "na();"); } a(); ■ almost trivial because Javascript gives you access to a function’s source code 22
  • 23. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Bootstrapping ■ An allusion to lift yourself up by your own bootstraps ■ Bootstrapping means using a special process to perform a task that one would be unable to do in general – for example, writing a compiler in terms of itself – start with a simple compiler, compile a more complex version in that one ■ When write a Quine – The program has a code part and a data part – The data part represents the entire code – But the code contains the data part – Seems like a paradox: how can the data part contain itself? – Bootstrapping needed: • put special character in data part • replace that character by the data part itself 23
  • 24. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Quine (C) 1/6 /* A simple quine (self-printing program), in standard C. */ /* Note: in designing this quine, we have tried to make the code clear * and readable, not concise and obscure as many quines are, so that * the general principle can be made clear at the expense of length. * In a nutshell: use the same data structure (called "progdata" * below) to output the program code (which it represents) and its own * textual representation. */ #include <stdio.h> void quote(const char *s) /* This function takes a character string s and prints the * textual representation of s as it might appear formatted * in C code. */ { int i; printf(" ""); ... 24
  • 25. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Quine (C) 2/6 for (i=0; s[i]; ++i) { /* Certain characters are quoted. */ if (s[i] == '') printf(""); else if (s[i] == '"') printf("""); else if (s[i] == 'n') printf("n"); /* Others are just printed as such. */ else printf("%c", s[i]); /* Also insert occasional line breaks. */ if (i % 48 == 47) printf(""n ""); } printf("""); } ... 25
  • 26. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Quine (C) 3/6 /* What follows is a string representation of the program code, * from beginning to end (formatted as per the quote() function * above), except that the string _itself_ is coded as two * consecutive '@' characters. */ const char progdata[] = "/* A simple quine (self-printing program), in st" "andard C. */nn/* Note: in designing this quine, " "we have tried to make the code clearn * and read" "able, not concise and obscure as many quines are" ", so thatn * the general principle can be made c" "lear at the expense of length.n * In a nutshell:" " use the same data structure (called "progdata"n" " * below) to output the program code (which it r" "epresents) and its ownn * textual representation" ". */nn#include <stdio.h>nnvoid quote(const char " "*s)n /* This function takes a character stri" "ng s and prints then * textual representati" "on of s as it might appear formattedn * in " "C code. */n{n int i;nn printf(" "");n ... 26
  • 27. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Quine (C) 4/6 " for (i=0; s[i]; ++i) {n /* Certain cha" "racters are quoted. */n if (s[i] == '')" "n printf("");n else if (s[" "i] == '"')n printf(""");n e" "lse if (s[i] == 'n')n printf("n");" "n /* Others are just printed as such. */n" " elsen printf("%c", s[i]);n " " /* Also insert occasional line breaks. */n " " if (i % 48 == 47)n printf(""" "n "");n }n printf(""");n}nn/* What fo" "llows is a string representation of the program " "code,n * from beginning to end (formatted as per" " the quote() functionn * above), except that the" " string _itself_ is coded as twon * consecutive " "'@' characters. */nconst char progdata[] =n@@;nn" "int main(void)n /* The program itself... */n" "{n int i;nn /* Print the program code, cha" "racter by character. */n for (i=0; progdata[i" "]; ++i) {n if (progdata[i] == '@' && prog" ... 27
  • 28. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Quine (C) 5/6 "data[i+1] == '@')n /* We encounter tw" "o '@' signs, so we must print the quotedn " " * form of the program code. */n {n " " quote(progdata); /* Quote all. */n" " i++; /* Skip second '" "@'. */n } elsen printf("%c", p" "rogdata[i]); /* Print character. */n }n r" "eturn 0;n}n"; int main(void) /* The program itself... */ { int i; /* Print the program code, character by character. */ for (i=0; progdata[i]; ++i) { if (progdata[i] == '@' && progdata[i+1] == '@') /* We encounter two '@' signs, so we must print the quoted * form of the program code. */ ... 28 look for two consecutive @ characters and replace them by program string itself
  • 29. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Quine (C) 6/6 { quote(progdata); /* Quote all. */ i++; /* Skip second '@'. */ } else printf("%c", progdata[i]); /* Print character. */ } return 0; } ■ Reflective questions (pun intended) – Is this a metaprogram? – Is it a reflective program? – Is it self-modifying? 29
  • 31. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Things to remember ■ Meta (programming) ■ (Computational) Reflection ■ Bootstrapping 31
  • 32. LSINF2335:Prog.Paradigms: Theory,Pract.andApplic. Comprehension exercises ■ Do you believe the Safir-Whorf hypothesis applies to programming ? ■ Write a paradoxical reflective sentence and explain why it is paradoxical ■ Is the following “definition” reflective? – recursive: adjective, see recursive ■ Explain reflection, metaprogramming and bootstrapping in your own words. ■ Explain the word “meta” without going meta. ■ Write a quine in a programming language of your choice. ■ Can you write one that makes use of reflection? ■ Are you programming reflectively when you use the keyword “this” in Java? ■ Read the book : “Gödel, Escher, Bach”. 32