Chapter 6. Predefined Predicates

Similar documents
CAP 5602 Summer, Lesson 4: Loops. The topics 1. the cut and some of its uses 2. the while loop 3. the do until loop

Lecture 9: A closer look at terms

Modules in SWI Prolog

IKI30820 Logic Programming Input and Output Slide 07

Combining Lists & Built-in Predicates

What s the problem? fib(1,1). fib(2,1). fib(n,x) :- N>2, N1 is N-1, N2 is N-2, fib(n1,x2), fib(n2,x2).

Implementação de Linguagens 2016/2017

C-LANGUAGE CURRICULAM

Lecture 9. Exercises. Theory. Solutions to exercises LPN 8.1 & 8.2. Patrick Blackburn, Johan Bos & Kristina Striegnitz

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Logic Programming (PLP 11.3) Prolog: Arithmetic, Equalities, Operators, I/O, Natural Language Parsing

Logic Programming (PLP 11) Prolog: Arithmetic, Equalities, Operators, I/O, Natural Language Parsing

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

Prolog Assessed Exercise

Logic Programming Prolog: Arithmetic, Equalities, Operators, I/O. (PLP 11) Databases: assert, retract. (CTM 9.6)

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Logic Programming. Efficiency Issues. Temur Kutsia

Full file at

Lecture 5: Declarative Programming. The Declarative Kernel Language Machine. September 12th, 2011

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

UNIT 3 OPERATORS. [Marks- 12]

Problem with Scanning an Infix Expression

Prolog-2 nd Lecture. Prolog Predicate - Box Model

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

Snakes. Declarative Languages. Relation different. Overview. Negation as failure. Relation different

Absolute C++ Walter Savitch

Logic Programming. Manipulating Programs. Temur Kutsia

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Lecture Notes on Memory Layout

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Part I Logic programming paradigm

3. Java - Language Constructs I

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Prolog. Intro to Logic Programming

CS 320: Concepts of Programming Languages

Prolog. Artificial Intelligence. Lecture 2 Karim Bouzoubaa

Logic Languages. Hwansoo Han

Introduction to Programming Using Java (98-388)

Chapter 2. Declarative Semantics

Information technology Programming languages Prolog Part 1: General core

Chapter 6 Fundamentals of the Logical Paradigm. Programming Languages and Paradigms J. Fenwick, B. Kurtz, C. Norris (to be published in 2012)

3 Lists. List Operations (I)

QUIZ: What value is stored in a after this

Page 1 of 5. University of Toronto CSC326 Programming Languages, Fall 2009

This lecture covers: Prolog s execution strategy explained more precisely. Revision of the elementary Prolog data types

EXPRESSIONS AND ASSIGNMENT CITS1001

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

The Typed Racket Guide

Wan Hussain Wan Ishak

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

An introduction to Prolog. P. Cabalar ( Department Prolog of Computer Science University of Corunna, FebruarySPAIN 8, 2016)

LECTURE 3 C++ Basics Part 2

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

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 1 IDL Operators

The Prolog to Mercury transition guide

Lecture 16: Logic Programming in Prolog

Input & Output. York University Department of Computer Science and Engineering. York University- CSE V. Movahedi 08_IO

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

Algebra 1 Review. Properties of Real Numbers. Algebraic Expressions

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Arithmetic type issues

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

Chapter 2: Data and Expressions

Programming Paradigms

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Assignment 1. University of Toronto, CSC384 - Introduction to Artificial Intelligence, Winter

UNIT- 3 Introduction to C++

What needs to be kept track of ffl The current substitution ffl The current goal ffl The clause currently in use ffl Backtrack Information 2

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Wan Hussain Wan Ishak

egrapher Language Reference Manual

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

OBJECT ORIENTED PROGRAMMING

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Prolog (cont d) Remark. Using multiple clauses. Intelligent Systems and HCI D7023E

Information Science 1

Arithmetic (12A) Young W. Lim 4/9/14

Recursion, Structures, and Lists

CS Programming In C

Computational Logic The (ISO-)Prolog Programming Language

Topic B: Backtracking and Lists

Chapter 3 Structure of a C Program

A second life for Prolog

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Visual C# Instructor s Manual Table of Contents

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

CS422 - Programming Language Design

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

CSE P 501 Exam 8/5/04

PROgramming in LOGic PROLOG Recursion, Lists & Predicates

Transcription:

Advanced Logic Programming https://sewiki.iai.uni-bonn.de/teaching/lectures/alp/2017/ Chapter 6. Predefined Predicates Updated: 12 June, 2017 Reorganized entire chapter Input and output Exception handling Type Checking Comparing Arithmetic

Files Naming and Locating File names use Unix notation ( / as separator) also on Windows! To use Windows notation each \ must be doubled, because \ is the escape character in Prolog atoms! (e.g. \t represents a tab). Aliases Aliases are defined via file_search_path(+alias, +Path) A file location relative to an alias is specified using the alias as a functor and adding the relative path as argument?- file_search_path(demo, /home/gk/prolog/demo ).?- absolute_file_name(demo(myfile), Absolute). Absolute = /home/gk/prolog/demo/myfile true. file_search_path/2 is used by absolute_file_name/[2,3] and all loading predicates?- prolog_flag( verbose_file_search, true) can be used to debug Prolog s search for files. 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 2

Prolog Files Compilation and Loading consult(+file) Compile and load prolog files make/0 Check which loaded files have been modified and reconsult them 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 4

Implicit versus Explicit I/O Three ways to happiness Explicit ISO style File opening creates a stream identifier open/3 All other file operations take a Stream identifier as parameter read/2, write/2 Implicit Edingburg style There is one global input and output seeing/1, telling/1 It is globally redirected see/1, tell/1 seen/1, told/1 Implicit SWI style Output of a predicate redirected at call site with_output_to/2 Special redirection to atoms strings 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 5

Streams I/O with Explicit Src/Dest (1) open(+file, +Mode,?Stream) open a stream File = file specifier pipe(command) A file specifier is a path or an alias. Mode = read, write, append or update. Mode append positions the file-pointer at the end. Mode update positions the file-pointer at the beginning of the file without truncating it. Stream is a variable, in which case it is bound to an integer identifying the stream, or an atom, in which case this atom will be the stream identifier. 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 6

Streams I/O with Explicit Src/Dest (2) current_stream(?file,?mode, +Stream) get the status of a stream current_stream( File,?Mode, Stream) enumerate all open streams Mode = read write set stream position(+stream, +Pos) Set current position of Stream to Pos. Many more stream handling predicates (see manual)! 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 7

Explicit versus Implicit I/O Three ways to happiness Explicit ISO style File opening creates a stream identifier open/3 All other file operations take a Stream identifier as parameter read/2, write/2 Implicit Edingburg style There is one global input and output seeing/1, telling/1 It is globally redirected see/1, tell/1 seen/1, told/1 Implicit SWI style Bad pass stream to all predicates that might need I/O or assert stream information Good Bad simple idiom for input switching global state interference possible 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 8

Files I/O with implicit Src/Dest (1) The reading predicates refer to the implicit current input stream The writing predicates refer to the implicit current output stream. Initially both are connected to the terminal / console. The current input stream is obtained using seeing/1. changed using see/1. closed using seen/0. The current output stream is obtained using telling/1 changed using tell/1 or append/1. closed using told/0. The arguments of these operations are either a file user (the reserved stream name for the terminal) pipe(command) Write at the end of the file?- see(data). % Start reading from file data.?- tell(user). % Start writing to the terminal.?- tell(pipe(lpr)). % Start writing to the printer. 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 9

Using Implicit Source Application example: Consulting a file consult(file) :- seeing(oldfile), see(file), % set input to File consult_loop, % read File and assert clauses seen, see(oldfile). % reset input to OldFile consult_loop repeat :- repeat, read(clause), process(clause),!. process(x) :- X == end_of_file. process(clause) :- assert(clause), fail fail. succeeds infinitely successful end trigger backtracking 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 10

Using Implicit Source and Destination Application example: Copying a file copy(input,output) :- seeing(oldinput),see(input), telling(oldoutput),tell(output), copy, seen, see(oldinput), told, tell(oldoutput). % set new input % set new output % do the real copying % reset old input % reset old output copy :- repeat, read(x), write(x), X == end_of_file,!. Recall that the idiom used in copy/0 corresponds to a do_until or do_whilenot loop in imperative languages See section on iteration via backtracking 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 11

Implicit versus Explicit I/O Three ways to happiness Explicit ISO style File opening creates a stream identifier open/3 All other file operations take a Stream identifier as parameter Bad read/2, write/2 pass stream to all predicates that might need I/O or assert stream information Implicit Edingburg style There is one global input and output seeing/1, telling/1 It is globally redirected Good Bad see/1, tell/1 seen/1, told/1 simple idiom for input switching global state interference possible Implicit SWI style Output of a predicate redirected at call site with_output_to/2 Special redirection to atoms strings Good Bad no crosscutting parameter passing no global state with_input_from/2 missing 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 12

SWI-Style example Asume a predicate that has nothing to do with I/O ancestor(a,d):- parent(a,d). copy :- repeat, read(x), write(x), X == end_of_file,!. Recall that the idiom used in copy/0 corresponds to a do_until or do_whilenot loop in imperative languages See section on iteration via backtracking 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 13

Homework (Exam training) To understand the practical effect of using ISO-style versus Edingburghstyle IO Find an example of problematic use of Edingburgh-style IO Rewrite the predicates on the previous two slides so that they use ISOstyle explicit streams Discuss your solution with a colleague who solved the task independently. Discuss which style you would prefer and why 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 14

Chapter 5: Predefined predicates Exception Handling setup_call_cleanup/3

Exception Handling Predicate setup_call_cleanup(setup, Call, Cleanup) First calls Setup Then calls Call Then calls Cleanup Cleanup is guaranteed to be executed no matter how Call terminated (success, failure or exception) 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 16

Exception Handling: Example 1 Use setup_call_cleanup(setup, Call, Cleanup) to close files properly in case of an exception. %% term_in_file(+term, +File) % Search Term in File, succeed as soon as Term is found and fail % if end_of_file is reached before finding it: term_in_file(term, File) :- setup_call_cleanup(open(file, read, In), term_in_stream(term, In), close(in) ). term_in_stream(term, In) :- repeat, read(in, T), ( T == end_of_file % if end of file is reached ->!, fail % then fail ; T = Term % else check if it is the sought term ). 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 17

Exception Handling: Example 2 Use setup_call_cleanup(setup, Call, Cleanup) for safe input / output redirection: %% with_input_from( +Stream, :Goal) is semidet. % % Switch current input to Stream, call Goal once, % then switch back to previous input stream. :- meta_predicate with_input_from(+,0). with_input_from(stream,goal) :- current_input(s0), % Remember current input setup_call_cleanup(set_input(stream), % Set input to Stream Goal, % Call Goal set_input(s0) % Reset the input ). 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 18

Chapter 5: Predefined predicates Type Checking Instantiation modes Term structure Numbers

Type-checking Built-in Predicates Testing instantiation modes var(x) is true when X is an unbound variable. nonvar(x) is true when X is not a variable or is bound to a variable Y for which nonvar(y) holds ground/1 argument contains no free variables -- e.g. 1, a, f(x,a) with X bound. 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 20

Type-checking Built-in Predicates Testing term structure atom(x) X is an atom (but not a number) atomic(x) atom(x) or number(x). compound(x) X is a compound term (a function term) cyclic_term(x) X is the result of applying a cyclic substituion acyclic_term(x) not cyclic_term(x) Testing numbers number(x) X is an integer or rational rational(x) rational includes integer integer(x) X is an integer float(x) X is a float 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 21

Chapter 5: Predefined predicates Comparing Numbers and Terms Comparing numbers Comparing terms

Comparing Numbers Arithmetic Notation x < y x y x > y x y x = y x y Prolog Operator X < Y X =< Y X > Y X >= Y X =:= Y not X=Y!!! X =\= Y not X\=Y!!! All operators that compare numbers 1. evaluate both arguments, 2. cast them appropriately, 3. compare the results 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 23

Comparing Numbers: Examples No surprises Note the difference!?- 2 < 4+1. yes?- 4 = 4. yes?- 2+2 =:= 4. yes?- 4+3 > 5+5. no?- 2+2 = 4. no?- 2+2 =:= 4.0. yes arithmetic > test unification arithmetic equality test 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 24

Comparing Numbers Warning: The is/2 predicate should not be used for testing equality Using it with unbound left operand can give unexpected results:?- 1 is sin(pi/2). false. The above fails because sin(pi/2) evaluates to the float 1.0, which does not unify with the integer 1 If equality of numbers is to be tested, =:=/2 should be used?- 1 =:= sin(pi/2). true. The above succeeds as expected because =:=/2 evaluates the righthand-side expression and casts it appropriately before it tries to unify it to the left-hand-side expression 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 25

Comparing Terms Operators that compare terms do not evaluate their arguments X @< Y X @> Y X @=< Y X @>= Y X == Y X \== Y smaller greater smaller or equal greater or equal identical not identical They compare them according to the standard order of terms Free Variable @< Number @< Atom @< String @< Compound Term Bound variables are sorted like the term to which they are bound Free variables are sorted by address Atoms are sorted alphabetically. Strings too. Numbers are sorted by value. Compound terms are sorted first on their arity, then on their functor and finally on their arguments, leftmost first. 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 26

Comparing Terms: Standard Order Standard order of terms Free Variable @< Number @< Atom @< String @< Compound Term Bound variables are sorted like the term to which they are bound Free variables are sorted by address Atoms are sorted alphabetically. Strings too. Numbers are sorted by value. Compound terms are sorted first on their arity, then on their functor and finally on their arguments, leftmost first.?- _G9669 @< _G9670. true?- X @< 1. true?- aaa @< b. true?- 2 @< 3. true?- f(b) @< a(a,a) true?- f(b,b) @< g(a,a). true?- f(b,b) @< f(c,a). true?- f(b,b) @< f(b,c). true?- X == Y. false?- X == X. true?- a == b. false?- a == a. true?- a == A. false?- a=a, a==a. true?- X=Y, X==Y. true?- X=2, Y=2, X==Y. true 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 27

Exercise: Write your own Comparison Define a predicate max_elem/2 that is true if: The first argument is a list of positive integers and the second argument is the highest integer in the list. Hint: Use a helper predicate that has an accumulator that remembers the highest value encountered so far (while traversing the initial part of the list).?- max_elem([1,0,5,4], Max). Max=5 Solution max_elem(l,max):- max_elem (L,0,Max). max_elem ([],A,A). max_elem ([H T],A,Max):- max_elem ([H T],A,Max):- H > A, max_elem (T,H,Max). H =< A, max_elem (T,A,Max). 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 30

Chapter 5: Predefined predicates Arithmetic is/2 predicate Defining own arithmetic functions

Arithmetic in Prolog Terms are not functions! Expressions such as 3+2, 4-7, 5/5 are ordinary Prolog terms They do not carry out any arithmetic (do not compute a result)!?- X = 3+2. % just unifies X to 3+2 X = 3+2 yes?- 3+2 = X. % just unifies X to 3+2 X = 3+2 yes 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 32

Arithmetic in Prolog: The is/2 predicate To actually evaluate arithmetic expressions, we must use the is/2 predicate It unifies the left-hand-side term with the result of evaluating the right-hand-side term as an arithmetic expression:?- X is 3+2. X = 5 true.?- 3+2 is 3+2. false.?- 3+2 = 3+2. true. Integer Arithmetic Whenever both arguments are integers When a floating point value is whole ( transformed into an integer). Floating point arithmetic if an argument is a non-whole floating point 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 33

Arithmetic in Prolog Any standard arithmetic operator can be evaluated by is/2 :?- X is 2+3. % X=5 addition?- X is 5-3. % X=2 subtraction?- X is 3 4. % X=12 multiplication?- X is 7/2. % X=3.5 division?- X is round(7/2). % X=4 rounding?- X is 7//2. % X=3 integer division?- X is mod(7,2). % X=1 modulo?- X is abs(-5-3). % X=8 absolute value?- X is max(2.5,3). % X=3 maximum?- X is float(max(2.5,3)). % X=3.0 casting to float?- X is random(1000). % 1 <= X <= 1000 SWI-Prolog supports arithmetic, triogonometry, casting, bitvector operations, and many more See SWI-Prolog manual, Section 4.26 Arithemetic?- help. and then search for arithmetic 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 34

(Un)Safe Invocation Modes The is/2 predicate requires the right-hand-side expression to be ground (at the time when is/2 is executed):?- 5 is X+2. ERROR: is/2: Arguments are not sufficiently instantiated?- X=3, Y is X+2. X = 3, Y = 5. Unsafe invocation modes = Invocation modes for which the predicate cannot be evaluated Typical for many built-in predicates E.g. is/2 with mode (?, nonground) is unsafe 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 35

Defining Arithmetic Functions arithmetic_function(+head) Register a new arithmetic function that can be used within the right-handside of an is/2 call +Head must be of the form Name/Arity, an atom or a function term. There must exist a predicate that has the name specified by Head and Arity+1 arguments The arguments on position 1 to Arity are input parameters that must be bound to numbers at call time. The last argument (on position Arity+1) must be unbound at call time and must be bound by the body of the predicate. It will be bound to the left-hand-side of the is/2 call. % Contents of file mean.pl : :- arithmetic_function(mean/2). mean(a, B, C) :- C is (A+B)/2.?- consult(mean). mean compiled, 0.07 sec, 440 bytes.?- A is mean(4,5). A = 4.500000 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 36

Summary File I/O File names and aliases Implicit, explicit and SWI-style I/O Type checking instantiation term structure numbers Exception handling setup_call_cleanup/3 Comparison numbers terms Arithmetic is/2 and own extensions 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 37

What s next? Browse the online documentation at http://www.swi-prolog.org/pldoc/doc_for?object=root Read about predefined libraries, e.g. socket handling http://www.swi-prolog.org/pldoc/doc/swi/library/socket.pl 2009-2017 Dr. G. Kniesel Course Advanced Logic Progrmming (ALP) Chapter 5, Slide 38