SlideShare a Scribd company logo
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

PDF
Basics of reflection
PDF
Reflection in Ruby
PDF
Basics of reflection in java
PPTX
Introduction to Ruby’s Reflection API
PPTX
Java Reflection @KonaTechAdda
PPTX
Reflection in Java
PPTX
Java reflection
PPT
Chapter 2 - Basic Elements of Java
Basics of reflection
Reflection in Ruby
Basics of reflection in java
Introduction to Ruby’s Reflection API
Java Reflection @KonaTechAdda
Reflection in Java
Java reflection
Chapter 2 - Basic Elements of Java

What's hot (20)

PDF
Understanding And Using Reflection
PPT
9781111530532 ppt ch05
PPT
9781111530532 ppt ch10
PPTX
A (too) Short Introduction to Scala
PPTX
Classes And Objects
PPTX
Procedural programming
PPT
9781111530532 ppt ch07
PPT
9781111530532 ppt ch03
PDF
Object Oriented Programming Lab Manual
PDF
ASE02 DMP.ppt
PPT
OOP in Java
PPT
Most Asked Java Interview Question and Answer
PPT
9781439035665 ppt ch05
DOCX
Java questions for viva
PPT
Chapter 13 - Recursion
PPSX
Short notes of oop with java
PPTX
01. Introduction to Programming
PPTX
OCP Java (OCPJP) 8 Exam Quick Reference Card
PDF
OOPs Concepts - Android Programming
PPTX
Object+oriented+programming+in+java
Understanding And Using Reflection
9781111530532 ppt ch05
9781111530532 ppt ch10
A (too) Short Introduction to Scala
Classes And Objects
Procedural programming
9781111530532 ppt ch07
9781111530532 ppt ch03
Object Oriented Programming Lab Manual
ASE02 DMP.ppt
OOP in Java
Most Asked Java Interview Question and Answer
9781439035665 ppt ch05
Java questions for viva
Chapter 13 - Recursion
Short notes of oop with java
01. Introduction to Programming
OCP Java (OCPJP) 8 Exam Quick Reference Card
OOPs Concepts - Android Programming
Object+oriented+programming+in+java
Ad

Similar to A gentle introduction to reflection (20)

PPTX
Paradigms
PPTX
Introduction to computing and Programming (ppt)
PPTX
Plc part 1
PDF
Are High Level Programming Languages for Multicore and Safety Critical Conver...
PPTX
Imperative programming
PDF
CS4200 2019 Lecture 1: Introduction
PDF
Programming languages and concepts by vivek parihar
PPTX
DMA113 Chap1
PDF
Themes for graduation projects 2010
PDF
Lec 1 25_jul13
PDF
Lecture_HPC_7_ProgrammingCSI32_Paradigms.pdf
PDF
Evolution of Programming Languages.pdf
PDF
Evolution of Programming Languages.pdf
PDF
Attention-based Models (DLAI D8L 2017 UPC Deep Learning for Artificial Intell...
PDF
PL Lecture 01 - preliminaries
PPT
Agile software development
PPTX
APP_All Five Unit PPT_NOTES.pptx
PPT
5-CEN6016-Chapter1.ppt
PDF
Антон Кириллов, ZeptoLab
PPT
1. Introduction to Software Engineering.ppt
Paradigms
Introduction to computing and Programming (ppt)
Plc part 1
Are High Level Programming Languages for Multicore and Safety Critical Conver...
Imperative programming
CS4200 2019 Lecture 1: Introduction
Programming languages and concepts by vivek parihar
DMA113 Chap1
Themes for graduation projects 2010
Lec 1 25_jul13
Lecture_HPC_7_ProgrammingCSI32_Paradigms.pdf
Evolution of Programming Languages.pdf
Evolution of Programming Languages.pdf
Attention-based Models (DLAI D8L 2017 UPC Deep Learning for Artificial Intell...
PL Lecture 01 - preliminaries
Agile software development
APP_All Five Unit PPT_NOTES.pptx
5-CEN6016-Chapter1.ppt
Антон Кириллов, ZeptoLab
1. Introduction to Software Engineering.ppt
Ad

More from kim.mens (20)

PDF
Software Maintenance and Evolution
PDF
Context-Oriented Programming
PDF
Software Reuse and Object-Oriented Programming
PDF
Bad Code Smells
PDF
Object-Oriented Design Heuristics
PDF
Software Patterns
PDF
Code Refactoring
PDF
Domain Modelling
PDF
Object-Oriented Application Frameworks
PDF
Towards a Context-Oriented Software Implementation Framework
PDF
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
PDF
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
PDF
Context-oriented programming
PDF
Advanced Reflection in Java
PDF
Introduction to Ruby
PDF
Introduction to Smalltalk
PDF
Managing the Evolution of Information Systems with Intensional Views and Rela...
PDF
Usage contracts (presented at SATToSE 2014 in L'Aquila, Italy)
PDF
Usage contracts in a nutshell
PPTX
INGI2252 Software Measures & Maintenance
Software Maintenance and Evolution
Context-Oriented Programming
Software Reuse and Object-Oriented Programming
Bad Code Smells
Object-Oriented Design Heuristics
Software Patterns
Code Refactoring
Domain Modelling
Object-Oriented Application Frameworks
Towards a Context-Oriented Software Implementation Framework
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Context-oriented programming
Advanced Reflection in Java
Introduction to Ruby
Introduction to Smalltalk
Managing the Evolution of Information Systems with Intensional Views and Rela...
Usage contracts (presented at SATToSE 2014 in L'Aquila, Italy)
Usage contracts in a nutshell
INGI2252 Software Measures & Maintenance

Recently uploaded (20)

PDF
An interstellar mission to test astrophysical black holes
PDF
Phytochemical Investigation of Miliusa longipes.pdf
PDF
ELS_Q1_Module-11_Formation-of-Rock-Layers_v2.pdf
PDF
MIRIDeepImagingSurvey(MIDIS)oftheHubbleUltraDeepField
PDF
CAPERS-LRD-z9:AGas-enshroudedLittleRedDotHostingaBroad-lineActive GalacticNuc...
PPTX
microscope-Lecturecjchchchchcuvuvhc.pptx
PPTX
Microbiology with diagram medical studies .pptx
PPTX
ANEMIA WITH LEUKOPENIA MDS 07_25.pptx htggtftgt fredrctvg
PDF
Biophysics 2.pdffffffffffffffffffffffffff
PPTX
SCIENCE10 Q1 5 WK8 Evidence Supporting Plate Movement.pptx
PPTX
DRUG THERAPY FOR SHOCK gjjjgfhhhhh.pptx.
PDF
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...
PDF
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
PDF
SEHH2274 Organic Chemistry Notes 1 Structure and Bonding.pdf
PPTX
Protein & Amino Acid Structures Levels of protein structure (primary, seconda...
PDF
. Radiology Case Scenariosssssssssssssss
PPTX
Taita Taveta Laboratory Technician Workshop Presentation.pptx
PPTX
cpcsea ppt.pptxssssssssssssssjjdjdndndddd
PDF
The scientific heritage No 166 (166) (2025)
PPTX
TOTAL hIP ARTHROPLASTY Presentation.pptx
An interstellar mission to test astrophysical black holes
Phytochemical Investigation of Miliusa longipes.pdf
ELS_Q1_Module-11_Formation-of-Rock-Layers_v2.pdf
MIRIDeepImagingSurvey(MIDIS)oftheHubbleUltraDeepField
CAPERS-LRD-z9:AGas-enshroudedLittleRedDotHostingaBroad-lineActive GalacticNuc...
microscope-Lecturecjchchchchcuvuvhc.pptx
Microbiology with diagram medical studies .pptx
ANEMIA WITH LEUKOPENIA MDS 07_25.pptx htggtftgt fredrctvg
Biophysics 2.pdffffffffffffffffffffffffff
SCIENCE10 Q1 5 WK8 Evidence Supporting Plate Movement.pptx
DRUG THERAPY FOR SHOCK gjjjgfhhhhh.pptx.
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
SEHH2274 Organic Chemistry Notes 1 Structure and Bonding.pdf
Protein & Amino Acid Structures Levels of protein structure (primary, seconda...
. Radiology Case Scenariosssssssssssssss
Taita Taveta Laboratory Technician Workshop Presentation.pptx
cpcsea ppt.pptxssssssssssssssjjdjdndndddd
The scientific heritage No 166 (166) (2025)
TOTAL hIP ARTHROPLASTY Presentation.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