Programming Languages Week 6 Exercises

Size: px
Start display at page:

Download "Programming Languages Week 6 Exercises"

Transcription

1 Programming Languages Week 6 Exercises 1 Logic programming in Python 1.1 Unification Unification is the process of making two things the same. Unifying an unbound variable and a value makes them the same by binding the value to the variable. Unifying two unbound variables makes them the same by ensuring they always refer to the same value; if either one is bound to a value, the other is automatically bound to it too. Two values can be unified too, provided they are exactly the same value. When unifying two things, we need to know whether the unification was successful. In other words, unification is like asking the question: Can I unify these two values to make them the same? When we combine this question with complex sets of facts about the world, we can often find multiple ways to make two things the same. The question is therefore more correctly stated: In what ways can I unify these two values to make them the same? This sounds like a loop, and that is exactly how we will model it in Python. (Even though unify() only succeeds once, the facts and rules we create with unify() can succeed many times.) The generator function unify(x, Y) will try to find a way to make X and Y the same. If a way is found, it will set X and/or Y (if one or other is a variable) to the correct value(s) and then to allow a loop body to run. In our program we can therefore write: for _ in unify(x, Y): print "do something with", get(x), "and", get(y) (The variable _ is a don t care variable. It has no useful value, and we always ignore it. The strange name is intended to remind us about that.) We can pass any Python values we like as arguments for the parameters X and Y, but we cannot use normal Python variables to store values during unification. (For one thing, our unify generator has to be able to modify the values of any variables that are passed to it as arguments. We therefore have to use value holders, or wrappers, around the actual values the variables are holding.) This only slightly complicates our programs, by requiring that we write or X = var() A, B, C = var(), var(), var() to create and store logic variable objects in our Python variables. It also means we have to use get(x) to retrieve the value stored in a logic variable called X. We should never assume that it is possible to assign to a logic variable. In fact, we never even try to assign to them directly. Instead we unify() them with the value we want to assign and then run some code if the unification succeeds. X = var() for _ in unify(x, 42): print "X was successfully set to", get(x) (In this example, X will be bound to 42 while the loop body runs once. After the loop body has run once, the variable X will be unbound again.) Note the capitalisation of logic variable names. Prolog progammers tend to capitalise their variable names, so we will too. (It also reminds us to use get() to retrieve their values in Python.)

2 1.2 A small unification library For our explorations we will use a small, home-made unification library. It does not do everything a serious logic programming library would do, but it is better for our needs because it implements the core mechanism of languages like Prolog, while being small enough to understand completely. 0. Open your favorite text editor 1 and enter the following program. Save it in a file called unify.py. class var(): def init (self): self. bound = False self.value= None def _assign(v, x): # _assign to remind people to use unify instead if not v. bound: v. value = x v. bound = True v. bound = False def get(v): if isinstance(v, var) and v. bound: return get(v. value) return v def unify(l, R): Lval, Rval = get(l), get(r) if isinstance(lval, var): for _ in _assign(lval, Rval): elif isinstance(rval, var): for _ in _assign(rval, Lval): else: if Lval == Rval: Then add this line to the beginning of any Python program you write that uses unification: from unify import * (You can download an annotated version of this library, with detailed comments explaining how it works, from here: 1. Try the following examples, to get a feel for how unify() works. from unify import * for _ in unify(123, 123): print "yay it works" for _ in unify(123, 321): print "boo it broke" You can see that unify() succeeds only when it can make its two arguments mean the same thing. 1 On Mac, TextEdit.app will work fine provided you make sure it is in plain text mode. On Windows you can download the free Notepad++ editor (from for editing code. (The Microsoft Notepad application is not recommended for anything more ambitious than making a shopping list, and even for that it is borderline useless.) Of course, on any platform, Emacs is by far the best choice if you are comfortable with it. 2

3 X = var() for _ in unify(x, 66): print get(x) for _ in unify(99, X): print get(x) These two succeed because unify can just assign the unbound variable X to the other argument (a literal value) to make them the same. If you now try print get(x) you will see that X is no longer bound to any value (and when printed it reports its true nature as a unify.var ). Y = var() for _ in unify(x, 66): for _ in unify(x, Y): print get(x), get(y) for _ in unify(x, Y): for _ in unify(x, 99): print get(x), get(y) These two examples demonstrate that it does not matter which order you unify two variables and a literal. Unifying one variable with a literal and then with another variable is the same as unifying the two variables first followed by unifying one of them to the literal. Z = var() for _ in unify(x, Y): for _ in unify(y, Z): for _ in unify(x, 1): print get(x), get(y), get(z) for _ in unify(y, 2): print get(x), get(y), get(z) for _ in unify(z, 3): print get(x), get(y), get(z) This example demonstrates that any number of variables can be unified. When any one of them is finally unified with a value, all of them immediately become bound to the same value. 2. Create a generator iseven(x) that unifies X with every even number between 0 and 8. The naïve solution to this exercise looks like this: def iseven(x): for _ in unify(x, 0): for _ in unify(x, 2): for _ in unify(x, 4): for _ in unify(x, 6): for _ in unify(x, 8): But remember that you can put anything you like inside your generator functions, including a normal for loop over a range of integers that are individually unified with a logic variable. Just remember to whenever you want to succeed with a new assignment of your argument variable(s). (In other words, re-write the above naïve solution to use a for and range instead.) Test your generator like this: for _ in iseven(x): print get(x), "is even" #=> [02468] is even 3

4 3. Write a generator istriple(x) that unifies X with every multiple of 3 between 0 and 9. Test it with: def istriple(n):... # fill in the blank for _ in istriple(x): print get(x), "is a multiple of 3" 4. Define generators that check for multiples of 2 or 3, and multiples of 2 and 3. (Do not use Python s built-in operators, such as or and and.) Test your generators like this: def mult2or3(x):... # fill in the blank def mult2and3(x):... # fill in the blank for _ in mult2or3(x): print get(x), "is multiple of 2 or 3" #=> [ ] is a multiple of 2 or 3 for _ in mult2and3(x): print get(x), "is multiple of 2 and 3" #=> [06] is multiple of 2 and 3 (Note that the order of your results will probably be different, but should contain the same digits.) 1.3 Creating a knowledge base and asking questions about it A knowledge base contains facts and rules. Facts are statements about concrete things and their properties. We can make some simple factual statements about the Clinton family using unify() Write a generator isclinton(p) that generates a sequence of strings: Bill, Hillary, and Chelsea. Here is one way to do it: def isclinton(p): for _ in unify(p, "Bill") : for _ in unify(p, " Hillary") : for _ in unify(p, " Chelsea") : Test your generator: Person = var() for _ in isclinton( Person): print get( Person), "is a Clinton" Note the name isclinton suggests a predicate. This is deliberate. You can read the above example as: For all values of Person that satisfy isclinton, run the print statement. If you think of unify as being the predicate are the same thing, the following should be easy to understand: for _ in isclinton( Person): for _ in unify(person, " Hillary"): print " there is a Clinton who has the name Hillary" for _ in unify(person, " Hillary"): for _ in isclinton( Person): print "the person who has the name Hillary is a Clinton" for _ in unify(person, " George"): for _ in isclinton( Person): print " George has infiltrated the Clinton family!" 2 There are no particular reasons for choosing the Clinton family, other than their convenient family tree and the number 42. 4

5 Facts can include statements about the simple relationships between things. For example, we know that Hillary has two brothers and Bill has one. 6. Write a generator function hasbrother(person, Brother) which embodies the facts that Hillary has brothers named Tony and Hugh, and that Bill has a brother named Roger. def hasbrother(person, Brother): for _ in unify(person, "Bill"): for _ in unify(brother, " Roger"):... # fill in the missing part for Hillary Test your new facts like this: Brother = var() for _ in hasbrother(person, Brother): print get( Person), "has a brother", get( Brother) #=> Bill has a brother Roger #=> Hillary has a brother Tony #=> Hillary has a brother Hugh 7. Write a generator function hasparent(person, Parent) which embodies the fact that Hillary and Bill are the parents of Chelsea. Test your generator like this: def hasparent(person, Parent):... # fill in the blank Parent = var() for _ in hasparent(person, Parent): print get( Person), "has a parent named", get( Parent) #=> Chelsea has a parent named Hillary #=> Chelsea has a parent named Bill Rules are statements about how things can be related according to their properties. The simplest kinds of rule say that some relationship is true if two facts are true at the same time. 8. Write a generator function hasuncle(n, U) that states the following general rule: if a nephew/niece N has a parent P, and if P has a brother U, then U is the uncle of N. Use your rule to check who has an uncle in the Clinton family, like this: def hasuncle(person, Uncle):... # fill in the blank Uncle = var() for _ in hasuncle(person, Uncle): print get( Person), "has an uncle", get( Uncle) #=> Chelsea has an uncle Tony #=> Chelsea has an uncle Hugh #=> Chelsea has an uncle Roger 5

6 1.4 A more complex example Consider this partial family tree of the House of Stuart (who were, once upon a long time ago, the kings and queens of Scotland, England, Ireland, and even parts of France). James I Charles I Elizabeth Catherine Charles II James II Sophia George I 9. Create generators ismale(p) and isfemale(p) that state facts about names of the male and female Stuarts, and hasparent(child, Parent) that states facts about their lineage. def ismale(p):... # fill in the blank def isfemale(p):... # fill in the blank def hasparent(child, Parent):... # fill in the blank 10. Write a generator isperson(p) that represents the following rule: P is a (Stuart) person if they are a male Stuart or a female Stuart. def isperson(p):... # fill in the blank Test your facts and rule: X = var() for _ in isperson(x): print get(x), "is a person" #=> James I is a person #=> Charles I is a person #=> Charles II is a person #=> James II is a person #=> George I is a person #=> Elizabeth is a person #=> Catherine is a person #=> Sophia is a person 6

7 11. Write a rule hasmother(child, Mother) which states that Mother must be a female parent of Child. Write another similar rule hasfather(child, Father). Test your rules: def hasmother(child, Parent):... # fill in the blank def hasfather(child, Parent):... # fill in the blank Y = var() for _ in hasmother(x, Y): print get(x), "has mother", get(y) for _ in hasfather(x, Y): print get(x), "has father", get(y) #=> Sophia has mother Elizabeth #=> George I has mother Sophia #=> Charles I has father James I #=> Elizabeth has father James I #=> Catherine has father Charles I #=> Charles II has father Charles I #=> James II has father Charles I 12. Write a rule haschild(parent, Child). (Think how to do this in the laziest way possible. You already have all the facts you need, so this rule should be very simple.) Test your rule: def haschild(parent, Child):... # fill in the blank for _ in haschild(x, Y): print get(x), "has child", get(y) Verify your answers against the family tree diagram. 13. Write the rule hasgrandparent(grandchild, Grandparent). def hasgrandparent( Grandchild, Grandparent):... # fill in the blank for _ in hasgrandparent(x, Y): print get(x), "has grandparent", get(y) Verify your answers against the family tree diagram. 14. Write the rule hasgreatgrandparent(grandchild, Greatgrandparent). def hasgreatgrandparent(c, GGP):... # fill in the blank for _ in hasgreatgrandparent(x, Y): print get(x), "has great - grandparent", get(y) Verify your answers against the family tree diagram. 15. Write rules for hassibling(person, Sibling), hassister(person, Sister), and hasbrother (Person, Brother). (Since brothers and sisters have the same parents, you can infer the answers without stating any more facts.) def hassibling(a, B):... # fill in the blank def hassister(a, B):... # fill in the blank def hasbrother(a, B):... # fill in the blank for _ in hasbrother(x, Y): print get(x), "has a brother", get(y) for _ in hassister (X, Y): print get(x), "has a sister", get(y) for _ in hassibling(x, Y): print get(x), "has a sibling", get(y) Verify your answers against the family tree diagram. 7

8 16. Your cousin is the son or daughter of your uncle or aunt. Your uncles and aunts are the brothers and sisters of your parents. Write a rule to find all the cousins in the House of Stuart. def hasuncle(a, B):... # fill in the blank def hasaunt(a, B):... # fill in the blank def hascousin(a, B):... # fill in the blank for _ in hascousin(x, Y): #=> Sophia has cousin Catherine #=> Sophia has cousin Charles II #=> Sophia has cousin James II #=> Catherine has cousin Sophia #=> Charles II has cousin Sophia #=> James II has cousin Sophia print get(x), " has cousin", get(y) 1.5 A completely different example The following progam creates a database describing stations on train lines around Kyoto. It then states some general rules about direct and indirect journeys between train stations. Lines = { "Biwako": ["Takatsuki", "Kyoto", "Yamashina", "Otsu", "Ishiyama", "Kusatsu"], "Kosei": ["Kyoto", "Yamashina", "Otsukyo", "Karasaki", "Sakamoto", "Ogoto -onsen"] } def hasstation(l, S): for line in Lines: for _ in unify(l, line): for station in Lines[ line]: for _ in unify(s, station): def direct(a, B): L = var() for _ in hasstation(l, A): for _ in hasstation(l, B): def indirect(a, B): for _ in direct(a, B): return # fail if there is any direct train def changeat(a, B, C): for _ in direct(a, C): for _ in direct(c, B): for _ in indirect(a, B): The final part of this example asks about several journeys, printing whether there is a direct connection between the origin and destination, or the names of the stations where a change of train allows the journey to be made indirectly. Type in the above facts and rules, then run the following queries: C = var() for a, b in [ ("Takatsuki", "Kusatsu"), ("Takatsuki", "Kyoto"), ("Takatsuki", "Otsukyo"), ("Yamashina", "Sakamoto"), ("Otsukyo", "Sakamoto") ]: for _ in direct(a, b): print " from", a, " to", b, " there is a direct train" for _ in changeat(a, b, C): print " from", a, " to", b, " change at", get(c) 17. Add facts about the Keihan (Sakamoto) line, which passes through these stations: Ishiyamadera, Zeze, Hamaotsu, Ano, Sakamoto. Add a rule describing how to change trains twice to make a journey. Ask your system how to travel from Takatsuki to Hamaotsu. (There should be only two routes.) 18. At each change of train, print the names of the arrival and departure lines. 8

Programming Languages

Programming Languages Logic programming in Prolog Programming Languages Week 7 Exercises Prolog programs consist of two parts: a knowledge base containing facts and rules, and one or more queries (or goals) that ask questions

More information

RELATIONSHIP TO PROBAND (RELATE)

RELATIONSHIP TO PROBAND (RELATE) RELATIONSHIP TO PROBAND (RELATE) Release 3.1 December 1997 - ii - RELATE Table of Contents 1 Changes Since Last Release... 1 2 Purpose... 3 3 Limitations... 5 3.1 Command Line Parameters... 5 4 Theory...

More information

Topic A: Introduction to Prolog

Topic A: Introduction to Prolog Topic A: Introduction to Prolog Recommended Exercises and Readings From Programming in Prolog (5 th Ed.) Exercises: 1.2, 1.3, 1.4, Readings: Chapters 1 and 2 1 2 Prolog Prolog: Programming in Logic A logic

More information

Week 7 Prolog overview

Week 7 Prolog overview Week 7 Prolog overview A language designed for A.I. Logic programming paradigm Programmer specifies relationships among possible data values. User poses queries. What data value(s) will make this predicate

More information

Week - 01 Lecture - 04 Downloading and installing Python

Week - 01 Lecture - 04 Downloading and installing Python Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 04 Downloading and

More information

Visual Prolog Tutorial

Visual Prolog Tutorial Visual Prolog Tutorial Jim Mims April 2008 (with modification by Danjie Zhu) Preface What is Prolog? Programming in Logic. Edinburgh syntax is the basis of ISO standard. High-level interactive language.

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

6.034 Artificial Intelligence, Fall 2006 Prof. Patrick H. Winston. Problem Set 1

6.034 Artificial Intelligence, Fall 2006 Prof. Patrick H. Winston. Problem Set 1 6.034 Artificial Intelligence, Fall 2006 Prof. Patrick H. Winston Problem Set 1 This problem set is due Wednesday, September 20. If you have questions about it, ask the TA email list. Your response will

More information

Introduction to Artificial Intelligence 2 nd semester 2016/2017. Chapter 8: First-Order Logic (FOL)

Introduction to Artificial Intelligence 2 nd semester 2016/2017. Chapter 8: First-Order Logic (FOL) Introduction to Artificial Intelligence 2 nd semester 2016/2017 Chapter 8: First-Order Logic (FOL) Mohamed B. Abubaker Palestine Technical College Deir El-Balah 1 Introduction Propositional logic is used

More information

Introduction to Prolog

Introduction to Prolog Introduction to Prolog David Woods dwoods@scss.tcd.ie Week 3 - HT Declarative Logic The Prolog programming language is, at its theoretical core, a declarative language. This is unlike more commonly used

More information

Log In or Create an Account

Log In or Create an Account Welcome to AFC Events Registration! Before beginning the registration process for an AFC Event, you should log in or create an account at store.afc.org. Log In or Create an Account When looking at the

More information

Chapter 16. Logic Programming. Topics. Unification. Resolution. Prolog s Search Strategy. Prolog s Search Strategy

Chapter 16. Logic Programming. Topics. Unification. Resolution. Prolog s Search Strategy. Prolog s Search Strategy Topics Chapter 16 Logic Programming Summary (resolution, unification, Prolog search strategy ) Disjoint goals The cut operator Negative goals Predicate fail Debugger / tracer Lists 2 Resolution Resolution

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

The current topic: Prolog. Announcements. Meaning of a Prolog rule. Prolog syntax. Reminder: The deadline for Lab 2 re-mark requests is Friday.

The current topic: Prolog. Announcements. Meaning of a Prolog rule. Prolog syntax. Reminder: The deadline for Lab 2 re-mark requests is Friday. The current topic: Prolog! Introduction! Object-oriented programming: Python! Functional programming: Scheme! Python GUI programming (Tkinter)! Types and values Logic programming: Prolog! Introduction

More information

Conditional Execution

Conditional Execution Conditional Execution Chapter 3 Python for Informatics: Exploring Information www.py4inf.com Unless otherwise ted, the content of this course material is licensed under a Creative Commons Attribution 3.0

More information

Write the function of following in Windows Operating System:

Write the function of following in Windows Operating System: Assignment - I (Lessons 1-6) 1. Answer any two of the following questions. Differentiate between RAM and EPROM? Describe major components of a computer. Differentiate between Inkjet Printer and Laser Printer?

More information

Conditional Execution

Conditional Execution Conditional Execution Chapter 3 Python for Informatics: Exploring Information www.pythonlearn.com x = 5 X < 10? Yes Conditional Steps Program: No print 'Smaller' x = 5 Output: if x < 10: X > 20? Yes print

More information

mond and a square both go to the number 4.

mond and a square both go to the number 4. A function machine is called one-to-one if every one of its inputs goes to a dierent output. Let's determine which of our functions from last week are one-to-one. 1. Is Katja's function machine one-to-one?

More information

CS 1110 Final, December 8th, Question Points Score Total: 100

CS 1110 Final, December 8th, Question Points Score Total: 100 CS 1110 Final, December 8th, 2016 This 150-minute exam has 8 questions worth a total of 100 points. Scan the whole test before starting. Budget your time wisely. Use the back of the pages if you need more

More information

Lecture #23: Conversion and Type Inference

Lecture #23: Conversion and Type Inference Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). Last modified: Fri Oct 20 10:46:40 2006 CS164:

More information

Cambridge International Examinations Cambridge International Advanced Subsidiary and Advanced Level

Cambridge International Examinations Cambridge International Advanced Subsidiary and Advanced Level Cambridge International Examinations Cambridge International Advanced Subsidiary and Advanced Level COMPUTER SCIENCE 9608/41 Paper 4 Further Problem-solving and Programming Skills October/November 2017

More information

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = Hello; Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). In Java, this is legal: Object x = "Hello";

More information

Agenda. CS301 Session 20. A logic programming trick. A simple Prolog program. Introduction to logic programming Examples Semantics

Agenda. CS301 Session 20. A logic programming trick. A simple Prolog program. Introduction to logic programming Examples Semantics CS301 Session 20 Introduction to logic programming Examples Semantics Agenda 1 2 A logic programming trick A two-way translator in two lines of code: translate([],[]). translate([word Words],[Mot Mots])

More information

CS 1110 Final, December 8th, Question Points Score Total: 100

CS 1110 Final, December 8th, Question Points Score Total: 100 CS 1110 Final, December 8th, 2016 This 150-minute exam has 8 questions worth a total of 100 points. Scan the whole test before starting. Budget your time wisely. Use the back of the pages if you need more

More information

Professor Hugh C. Lauer CS-1004 Introduction to Programming for Non-Majors

Professor Hugh C. Lauer CS-1004 Introduction to Programming for Non-Majors Objects (again) Professor Hugh C. Lauer CS-1004 Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An Introduction to Computer Science, 2 nd edition, by John

More information

DRAWING ENVIRONMENT DIAGRAMS

DRAWING ENVIRONMENT DIAGRAMS DRAWING ENVIRONMENT DIAGRAMS COMPUTER SCIENCE 61A September 10, 2012 0.1 Background A frame is a location where variable bindings are stored A binding is a connection between a name and a value. The name

More information

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1 EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1 COMPUTER SCIENCE 61A June 24, 2014 0.1 Warmup What Would Python Do? >>> x = 6 >>> def square(x):... return x * x >>> square(x) >>> max(pow(2, 3), square(-5)) -

More information

Lists How lists are like strings

Lists How lists are like strings Lists How lists are like strings A Python list is a new type. Lists allow many of the same operations as strings. (See the table in Section 4.6 of the Python Standard Library Reference for operations supported

More information

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference Lecture #13: Type Inference and Unification Typing In the Language ML Examples from the language ML: fun map f [] = [] map f (a :: y) = (f a) :: (map f y) fun reduce f init [] = init reduce f init (a ::

More information

Programming Language Concepts (20013) Preparation for the Final Exam

Programming Language Concepts (20013) Preparation for the Final Exam Programming Language Concepts (20013) Preparation for the Final Exam This is a collection of 12 questions which are close to what is to be expected within the final exams for PLC. Sample answers to the

More information

INF5390 Kunstig intelligens. First-Order Logic. Roar Fjellheim

INF5390 Kunstig intelligens. First-Order Logic. Roar Fjellheim INF5390 Kunstig intelligens First-Order Logic Roar Fjellheim Outline Logical commitments First-order logic First-order inference Resolution rule Reasoning systems Summary Extracts from AIMA Chapter 8:

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Summer 2016 Structure and Interpretation of Computer Programs Midterm Solutions INSTRUCTIONS You have 2 hours and 50 minutes to complete the exam. The exam is closed book, closed notes, closed computer,

More information

CMSC 201 Spring 2019 Lab 06 Lists

CMSC 201 Spring 2019 Lab 06 Lists CMSC 201 Spring 2019 Lab 06 Lists Assignment: Lab 06 Lists Due Date: Thursday, March 7th by 11:59:59 PM Value: 10 points This week s lab will put into practice the concepts you learned about lists: indexing,

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators CS 61A Control and Environments Fall 2017 Discussion 1: August 30, 2017 1 Control Control structures direct the flow of logic in a program. For example, conditionals (if-elif-else) allow a program to skip

More information

CONTROL AND ENVIRONMENTS 1

CONTROL AND ENVIRONMENTS 1 CONTROL AND ENVIRONMENTS 1 COMPUTER SCIENCE 61A September 1, 2016 1 Control Control structures direct the flow of logic in a program. For example, conditionals (ifelif-else) allow a program to skip sections

More information

Programming Languages Prolog Programming Project Due Wednesday, December 5 th, 2001

Programming Languages Prolog Programming Project Due Wednesday, December 5 th, 2001 Programming Languages Prolog Programming Project Due Wednesday, December 5 th, 2001 How Prolog Works Although Prolog is a very powerful and expressive programming environment, it is surprisingly easy to

More information

Application for anonymous registration. How do I register as an anonymous elector? Returning the form. More information

Application for anonymous registration. How do I register as an anonymous elector? Returning the form. More information Application for anonymous registration You need to be on the electoral register to vote in elections and referendums. If the safety of you (or someone in your household) would be at risk if your name or

More information

SEMANTICS. Retrieval by Meaning

SEMANTICS. Retrieval by Meaning SEMANTICS 1 Retrieval by Meaning Query: "Accident of a Mercedes" Retrieved image: Methods for retrieval by meaning: high-level image understanding beyond state-of-the-art except easy cases natural language

More information

Introduction to Prolog by

Introduction to Prolog by to Prolog by a talk given to The Linux Supporters Group Adelaide July 2009 Slide 1 Choice Points in Prolog Slide 2 Prolog s run-time stack does not function as procedural language stacks do. It isn t even

More information

CS61A Notes Week 13: Interpreters

CS61A Notes Week 13: Interpreters CS61A Notes Week 13: Interpreters Read-Eval Loop Unlike Python, the result of evaluating an expression is not automatically printed. Instead, Logo complains if the value of any top-level expression is

More information

CMSC 201 Spring 2017 Lab 05 Lists

CMSC 201 Spring 2017 Lab 05 Lists CMSC 201 Spring 2017 Lab 05 Lists Assignment: Lab 05 Lists Due Date: During discussion, February 27th through March 2nd Value: 10 points (8 points during lab, 2 points for Pre Lab quiz) This week s lab

More information

CS 151 Name Final Exam December 17, 2014

CS 151 Name Final Exam December 17, 2014 Note that there are 10 equally-weighted qeustions. CS 151 Name Final Exam December 17, 2014 1. [20 points] Here is a list of data: 4 2 18 1 3 7 9 0 5. For each of the following structures I will walk through

More information

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

EE 368. Weeks 5 (Notes)

EE 368. Weeks 5 (Notes) EE 368 Weeks 5 (Notes) 1 Chapter 5: Trees Skip pages 273-281, Section 5.6 - If A is the root of a tree and B is the root of a subtree of that tree, then A is B s parent (or father or mother) and B is A

More information

/99/$ IEEE

/99/$ IEEE A Multiparadigm Language Approach to Teaching Principles of Programming Languages D. Suzanne Westbrook Computer Science and Electrical Engineering Northern Arizona University Flagstaff, AZ 86011 Abstract

More information

A secret of bees 1 MODELLING EXERCISE. (by Thilo Gross)

A secret of bees 1 MODELLING EXERCISE. (by Thilo Gross) A secret of bees 1 Bees have interesting family trees. A male bee, a so-called drone (D) only has one parent, who is a queen (Q). A queen has two parents, a queen and a drone. So a drone has only one parent,

More information

Understanding Recursion

Understanding Recursion Understanding Recursion sk, rob and dbtucker (modified for CS 536 by kfisler) 2002-09-20 Writing a Recursive Function Can we write the factorial function in AFunExp? Well, we currently don t have multiplication,

More information

Prolog. GNU Prolog ( SWI-Prolog (

Prolog. GNU Prolog (  SWI-Prolog ( Logic programming Most computations are directed, progressing from an input to an output. In functional programming, this is made very explicit, as the input is the argument of a function and the output

More information

6.034 Notes: Section 11.1

6.034 Notes: Section 11.1 6.034 Notes: Section 11.1 Slide 11.1.1 We've now spent a fair bit of time learning about the language of first-order logic and the mechanisms of automatic inference. And, we've also found that (a) it is

More information

CS 151 Name Final Exam December 17, 2014

CS 151 Name Final Exam December 17, 2014 Note that there are 10 equally-weighted qeustions. CS 151 Name Final Exam December 17, 2014 1. [20 points] Here is a list of data: 4 2 18 1 3 7 9 0 5. For each of the following structures I will walk through

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

MITOCW watch?v=zm5mw5nkzjg

MITOCW watch?v=zm5mw5nkzjg MITOCW watch?v=zm5mw5nkzjg The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information

Decisions, Decisions. Testing, testing C H A P T E R 7

Decisions, Decisions. Testing, testing C H A P T E R 7 C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little

More information

In this packet, you will find the forms necessary for your child to apply to the Registry. To apply, please complete the following steps:

In this packet, you will find the forms necessary for your child to apply to the Registry. To apply, please complete the following steps: Dear Registry Applicant, Thank you for your interest in the National Registry of Myotonic Dystrophy and Facioscapulohumeral Muscular Dystrophy Patients and Family Members! The Registry was established

More information

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators CS 61A Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions 1 Control Control structures direct the flow of logic in a program. For example, conditionals (if-elif-else) allow a program

More information

Red-Black trees are usually described as obeying the following rules :

Red-Black trees are usually described as obeying the following rules : Red-Black Trees As we have seen, the ideal Binary Search Tree has height approximately equal to log n, where n is the number of values stored in the tree. Such a BST guarantees that the maximum time for

More information

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators CS 61A Control and Environments Spring 2018 Discussion 1: January 24, 2018 1 Control Control structures direct the flow of logic in a program. For example, conditionals (if-elif-else) allow a program to

More information

CS 321 Programming Languages and Compilers. Prolog

CS 321 Programming Languages and Compilers. Prolog CS 321 Programming Languages and Compilers Prolog Prolog PROgramming LOGic Algorithm = Logic + Control Logic programming deals with computing relations rather than functions. To understand Prolog one must

More information

A Tale Dark and Grimm

A Tale Dark and Grimm Introduction 1. What happens to the point of view on the first page Page # 2. What is the bold writing in the book trying to show you? Page # 3. What does the King make Johannes promise him before he dies

More information

Linkage analysis with paramlink Session I: Introduction and pedigree drawing

Linkage analysis with paramlink Session I: Introduction and pedigree drawing Linkage analysis with paramlink Session I: Introduction and pedigree drawing In this session we will introduce R, and in particular the package paramlink. This package provides a complete environment for

More information

Type Checking. Outline. General properties of type systems. Types in programming languages. Notation for type rules.

Type Checking. Outline. General properties of type systems. Types in programming languages. Notation for type rules. Outline Type Checking General properties of type systems Types in programming languages Notation for type rules Logical rules of inference Common type rules 2 Static Checking Refers to the compile-time

More information

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid: 1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,

More information

Outline. General properties of type systems. Types in programming languages. Notation for type rules. Common type rules. Logical rules of inference

Outline. General properties of type systems. Types in programming languages. Notation for type rules. Common type rules. Logical rules of inference Type Checking Outline General properties of type systems Types in programming languages Notation for type rules Logical rules of inference Common type rules 2 Static Checking Refers to the compile-time

More information

C ONTROL AND H IGHER O RDER F UNCTIONS

C ONTROL AND H IGHER O RDER F UNCTIONS Name: Date: Period: Name 2: Name 3: Name 4: 20 points C ONTROL AND H IGHER O RDER F UNCTIONS (Review questions from readings and labs) 1 Instructions: Complete all 9S CIENCE discussion C OMPUTER 61A questions.

More information

! model construction

! model construction Logics of Image Interpretation 1 Describing Image Interpretation in Logical Terms In 2D images (with possible occlusions) we never see the complete 3D reality.? deduction! model construction "from the

More information

Q &A on Entity Relationship Diagrams. What is the Point? 1 Q&A

Q &A on Entity Relationship Diagrams. What is the Point? 1 Q&A 1 Q&A Q &A on Entity Relationship Diagrams The objective of this lecture is to show you how to construct an Entity Relationship (ER) Diagram. We demonstrate these concepts through an example. To break

More information

Lesson #17 Function Introduction

Lesson #17 Function Introduction Lesson #17 Function Introduction A.A.37 A.A.40 A.A.41 Define a relation and function Write functions in functional notation Use functional notation to evaluate functions for given values in the domain

More information

Do not turn this page until you have received the signal to start. In the meantime, please read the instructions below carefully.

Do not turn this page until you have received the signal to start. In the meantime, please read the instructions below carefully. CSC 148 H1 / L0101 Term Test # 2 13 March 2013 Duration: Aids Allowed: 50 minutes None Student Number: Last (Family) Name(s): First (Given) Name(s): Do not turn this page until you have received the signal

More information

Fuzzy Rogers Research Computing Administrator Materials Research Laboratory (MRL) Center for Scientific Computing (CSC)

Fuzzy Rogers Research Computing Administrator Materials Research Laboratory (MRL) Center for Scientific Computing (CSC) Intro to R Fuzzy Rogers Research Computing Administrator Materials Research Laboratory (MRL) Center for Scientific Computing (CSC) fuz@mrl.ucsb.edu MRL 2066B Sharon Solis Paul Weakliem Research Computing

More information

4.2 Function definitions the basics

4.2 Function definitions the basics 4.2. FUNCTION DEFINITIONS THE BASICS 89 4.2 Function definitions the basics There are three questions you must answer before you can write a function definition: What will the function do? What inputs

More information

CMSC 201 Computer Science I for Majors

CMSC 201 Computer Science I for Majors CMSC 201 Computer Science I for Majors Lecture 02 Intro to Python Syllabus Last Class We Covered Grading scheme Academic Integrity Policy (Collaboration Policy) Getting Help Office hours Programming Mindset

More information

Prolog Programming. Lecture Module 8

Prolog Programming. Lecture Module 8 Prolog Programming Lecture Module 8 Prolog Language Prolog is unique in its ability to infer facts from the given facts and rules. In Prolog, an order of clauses in the program and goals in the body of

More information

Pattern Maker Lab. 1 Preliminaries. 1.1 Writing a Python program

Pattern Maker Lab. 1 Preliminaries. 1.1 Writing a Python program Pattern Maker Lab Lab Goals: In this lab, you will write a Python program to generate different patterns using ASCII characters. In particular, you will get practice with the following: 1. Printing strings

More information

CS 360: Programming Languages Lecture 10: Logic Programming with Prolog

CS 360: Programming Languages Lecture 10: Logic Programming with Prolog CS 360: Programming Languages Lecture 10: Logic Programming with Prolog Geoffrey Mainland Drexel University Section 1 Administrivia Midterm Tuesday Midterm is Tuesday, February 14! Study guide is on the

More information

First-Order Logic (FOL)

First-Order Logic (FOL) First-Order Logic (FOL) FOL consists of the following parts: Objects/terms Quantified variables Predicates Logical connectives Implication Objects/Terms FOL is a formal system that allows us to reason

More information

The object level in Prolog. Meta-level predicates and operators. Contents. The flow of computation. The meta level in Prolog

The object level in Prolog. Meta-level predicates and operators. Contents. The flow of computation. The meta level in Prolog Lecture 8 Meta-level predicates and operators Contents Object level vs. meta level Controlling flow of computation Checking and dismantling expressions Comparison operators The object level in Prolog Prolog

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

Recursion in Python. Recursive Functions. >>> 'pig'[0] 'p' >>> 'pig'[1:] 'ig'

Recursion in Python. Recursive Functions. >>> 'pig'[0] 'p' >>> 'pig'[1:] 'ig' Recursion in Python One of the fundamental ideas of computer science is to divide a complicated problem into one or more simpler pieces, solving them, and using their solution to compute a solution to

More information

Welfare Navigation Using Genetic Algorithm

Welfare Navigation Using Genetic Algorithm Welfare Navigation Using Genetic Algorithm David Erukhimovich and Yoel Zeldes Hebrew University of Jerusalem AI course final project Abstract Using standard navigation algorithms and applications (such

More information

MITOCW watch?v=w_-sx4vr53m

MITOCW watch?v=w_-sx4vr53m MITOCW watch?v=w_-sx4vr53m The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high-quality educational resources for free. To

More information

Logic Programming. Let us have airline flight information of the form: 1. Application Domains: 2. Definitions

Logic Programming. Let us have airline flight information of the form: 1. Application Domains: 2. Definitions Logic Programming 1. Application Domains: Logic programming language application areas include natural language processing, expert systems, specifications checking, theorem proving, and control systems

More information

GPS: The general problem solver. developed in 1957 by Alan Newel and Herbert Simon. (H. Simon, 1957)

GPS: The general problem solver. developed in 1957 by Alan Newel and Herbert Simon. (H. Simon, 1957) GPS: The general problem solver developed in 1957 by Alan Newel and Herbert Simon (H. Simon, 1957) GPS: The general problem solver developed in 1957 by Alan Newel and Herbert Simon - Was the first program

More information

ENVIRONMENT DIAGRAMS AND RECURSION 2

ENVIRONMENT DIAGRAMS AND RECURSION 2 ENVIRONMENT DIAGRAMS AND RECURSION 2 COMPUTER SCIENCE 61A February 4, 2016 1 Environment Diagrams An environment diagram keeps track of all the variables that have been defined and the values they are

More information

Logic-Oriented Programming (5/11/2004)

Logic-Oriented Programming (5/11/2004) 1 Logic-Oriented Programming (5/11/2004) Daniel P. Friedman, David W. Mack, William E. Byrd Computer Science Department, Indiana University Bloomington, IN 47405, USA Oleg Kiselyov Fleet Numerical Meteorology

More information

Notes for Chapter 12 Logic Programming. The AI War Basic Concepts of Logic Programming Prolog Review questions

Notes for Chapter 12 Logic Programming. The AI War Basic Concepts of Logic Programming Prolog Review questions Notes for Chapter 12 Logic Programming The AI War Basic Concepts of Logic Programming Prolog Review questions The AI War How machines should learn: inductive or deductive? Deductive: Expert => rules =>

More information

10. A Weekend to Remember

10. A Weekend to Remember 10. A Weekend to Remember Weekends don't count unless you spend them doing something completely pointless. Bill Watterson. Programming constructs and algorithmic paradigms covered in this puzzle: Graph

More information

Prolog Concepts. Programming for Beginners, Summer 2012

Prolog Concepts. Programming for Beginners, Summer 2012 Programming for Beginners, Summer 2012 Prolog Concepts Prolog is a logic programming language. Instead of expressing a sequence of actions to perform, Prolog programmers can (to a certain extent) describe

More information

Exercise 3: Objects, Design by Contract. Master Solution

Exercise 3: Objects, Design by Contract. Master Solution Exercise 3: Objects, Design by Contract Hand-out: 23 April 2004 Due: 30 April 2004 Master Solution 1. Summary: Objects, Design by Contract 1.1 Feature categories No result Command Procedure No result Routine

More information

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >:

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >: 3.4. FOR-LOOPS 65 3.4 For-loops In the previous section we looked at while-loops, Python s basic looping structure. There is a second loop construct in Python called a for-loop. This is more specialized.

More information

Backtracking. Backtracking. Backtracking. Backtracking. Backtracking. Backtracking. Functional & Logic Programming - Backtracking October, 01

Backtracking. Backtracking. Backtracking. Backtracking. Backtracking. Backtracking. Functional & Logic Programming - Backtracking October, 01 Functional & Logic Programming - October, 01 already seen how to control execution ordering the clauses and goals can affect the speed of execution and the order of evaluation of the clauses now going

More information

Multi-agent and Semantic Web Systems: Representation

Multi-agent and Semantic Web Systems: Representation Multi-agent and Semantic Web Systems: Representation Fiona McNeill School of Informatics 21st January 2013 21st January 2013 0/22 What kind of representation? There are many different kinds of representations

More information

MITOCW watch?v=kz7jjltq9r4

MITOCW watch?v=kz7jjltq9r4 MITOCW watch?v=kz7jjltq9r4 PROFESSOR: We're going to look at the most fundamental of all mathematical data types, namely sets, and let's begin with the definitions. So informally, a set is a collection

More information

Introduction to Java Programming

Introduction to Java Programming Boaz Kantor Introduction to Computer Science, Fall semester 2009-2010 IDC Herzliya Welcome, geeks! Introduction to Java Programming Plan for today: 1. Before we begin.. 2. What is Java? 3. How to program?

More information

(Refer Slide Time: 02.06)

(Refer Slide Time: 02.06) Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 27 Depth First Search (DFS) Today we are going to be talking

More information

Structured Knowledge Representation

Structured Knowledge Representation Intelligent Systems: Reasoning and Recognition James L. Crowley ENSIMAG 2 / MoSIG M1 Second Semester 2015/2016 Lesson 17 15 April 2016 Structured Knowledge Representation Object Oriented Programming...2

More information

Spam. Time: five years from now Place: England

Spam. Time: five years from now Place: England Spam Time: five years from now Place: England Oh no! said Joe Turner. When I go on the computer, all I get is spam email that nobody wants. It s all from people who are trying to sell you things. Email

More information

Lecture 8. Conditionals & Control Flow

Lecture 8. Conditionals & Control Flow Lecture 8 Conditionals & Control Flow Announcements For This Lecture Readings Sections 5.1-5.7 today Chapter 4 for Tuesday Assignment 2 Posted Today Written assignment Do while revising A1 Assignment 1

More information