Chapter 6 Data Types ISBN 0-321—49362-1 Chapter 6 Topics • • • • • • • • • Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer and Reference Types Copyright © 2007 Addison-Wesley. All rights reserved. 1-2 Introduction • A data type defines a collection of data objects and a set of predefined operations on those objects • A type system • Defines how a type is associated with each expression in the language • Includes rules for type equivalence and type compatibility • Design issues for data types: • What operations are defined and how are they specified? • Can users define new types gather clean and consistent data. Copyright © 2007 Addison-Wesley. All rights reserved. 1-3 Definitions • A descriptor is the collection of the attributes of a variable • Descriptors are used for type checking and to build the code for the allocation and deallocation operations • An object represents an instance of a user-defined (abstract data) type Copyright © 2007 Addison-Wesley. All rights reserved. 1-4 Primitive Data Types • Almost all programming languages provide a set of primitive data types • Primitive data types: Those not defined in terms of other data types • Some primitive data types are merely reflections of the hardware • Others require only a little non-hardware support for their implementation Copyright © 2007 Addison-Wesley. All rights reserved. 1-5 Primitive Data Types: Integer • Most common primitive numeric data type • There may be as many as eight different integer types in a language • Java’s signed integer sizes: byte, short, int, long • Most integer types are supported directly by the hardware Copyright © 2007 Addison-Wesley. All rights reserved. 1-6 Primitive Data Types: Floating Point • Model real numbers, but only as approximations • Languages include two floating-point types (e.g., float and double; sometimes more) • double (8 bytes) needs more space in memory than float(4 bytes) Copyright © 2007 Addison-Wesley. All rights reserved. 1-7 Primitive Data Types: Floating Point • Floating-point values are represented by fractions and exponents • IEEE Floating-Point Standard 754 Copyright © 2007 Addison-Wesley. All rights reserved. 1-8 Primitive Data Types: Floating Point • Floating-point values are represented by fractions and exponents • IEEE Floating-Point Standard 754 Copyright © 2007 Addison-Wesley. All rights reserved. 1-9 Primitive Data Types: Complex • Some languages support a complex type, e.g., Fortran and Python • Each value consists of two floats, the real part and the imaginary part • Literal form (in Python): (7 + 3j), where 7 is the real part and 3 is the imaginary part Copyright © 2007 Addison-Wesley. All rights reserved. 1-10 Primitive Data Types: Decimal • For business applications (money) – Essential to COBOL – C# offers a decimal data type • Store a fixed number of decimal digits, in coded form (BCD) Copyright © 2007 Addison-Wesley. All rights reserved. 1-11 Primitive Data Types: Boolean • Simplest of all • Range of values: two elements, one for “true” and one for “false” • C89: all operands with nonzero values are considered true, and zero is considered false when used in conditionals • C99 and C++ have a boolean type, but they also allow numeric expressions to be used. • Could be implemented as bits, but often as bytes – Advantage: readability Copyright © 2007 Addison-Wesley. All rights reserved. 1-12 Primitive Data Types: Character • Stored as numeric codings • Most commonly used coding: ASCII - Uses 0 to 127 codes to code 128 different characters • An alternative, 16-bit coding: Unicode – Includes characters from most natural languages – First 128 characters are identical to ASCII – Originally used in Java – C# and JavaScript also support Unicode Copyright © 2007 Addison-Wesley. All rights reserved. 1-13 Character String Types • Values are sequences of characters • Design issues: – Should the length of strings be static or dynamic? – Is it a primitive type or just a special kind of array? • It is up to language. • In C and C++: char str [] = “apples”; Copyright © 2007 Addison-Wesley. All rights reserved. 1-14 Character String Types in Java Copyright © 2007 Addison-Wesley. All rights reserved. 1-15 Character String Types Operations • Typical operations: – – – – – Assignment and copying Comparison (=, >, etc.) Catenation Substring reference Pattern matching Copyright © 2007 Addison-Wesley. All rights reserved. 1-16 Character String Type in Certain Languages • C and C++ – Not primitive – Use char arrays and a library of functions that provide operations (string.h) – strcpy: moves strings strcat: catenates one string onto another strcmp: compares two strings (by the order of their character codes) strlen: returns the number of characters • Java and Python – Primitive via the String class Copyright © 2007 Addison-Wesley. All rights reserved. 1-17 Character String Length Options • Static Length: COBOL, Java’s String class - Length is set when the string is created, fixed length • Limited Dynamic Length: C and C++ – Length is set to have a maximum, varying length • Dynamic Length (no maximum): SNOBOL4, Perl, JavaScript - No length limit, varying length. • Ada supports all three string length options Copyright © 2007 Addison-Wesley. All rights reserved. 1-18 Character String Implementation • Static length: compile-time descriptor Compile-time descriptor for static strings Copyright © 2007 Addison-Wesley. All rights reserved. 1-19 Character String Implementation • Limited dynamic length: may need a runtime descriptor for length (but not in C and C++) Run-time descriptor for limited dynamic strings Copyright © 2007 Addison-Wesley. All rights reserved. 1-20 Character String Implementation • Dynamic length: need simpler run-time descriptor; Run-time descriptor for dynamic strings Copyright © 2007 Addison-Wesley. All rights reserved. 1-21 User-Defined Ordinal Types • An ordinal type is one in which the range of possible values can be easily associated with the set of positive integers • Examples of primitive ordinal types in Java – integer – char – boolean • Two user-defined ordinal types - enumeration - subrange Copyright © 2007 Addison-Wesley. All rights reserved. 1-22 Enumeration Types • All possible values, which are named constants, are provided in the definition • Enumeration types provide a way of defining and grouping collections of named constants, which are called enumeration constants • C# example enum days {mon, tue, wed, thu, fri, sat, sun}; Copyright © 2007 Addison-Wesley. All rights reserved. 1-23 Evaluation of Enumerated Type • Aid to readability, e.g., no need to code a color as a number (C++ example) - Instead of int red = 0, int blue = 1 -enum colors = {red, blue, green, yellow, black} - colors myColor = blue, yourColor = red; - myColor++ - myColor = 4; Copyright © 2007 Addison-Wesley. All rights reserved. 1-24 Evaluation of Enumerated Type • Aid to reliability, e.g., compiler can check: – operations (don’t allow colors to be added) – No enumeration variable can be assigned a value outside its defined range – Ada, C#, and Java 5.0 provide better support for enumeration than C++ because enumeration type variables in these languages are not coerced into integer types Copyright © 2007 Addison-Wesley. All rights reserved. 1-25 Subrange Types • An ordered contiguous subsequence of an ordinal type - Example: 12..18 is a subrange of integer type • Included in Pascal and Ada • Ada’s design type Days is (mon, tue, wed, thu, fri, sat, sun); subtype Weekdays is Days range mon..fri; subtype Index is Integer range 1..100; Day1: Days; Day2: Weekdays; Day2 := Day1; Copyright © 2007 Addison-Wesley. All rights reserved. 1-26 Subrange Evaluation • Aid to readability – Make it clear to the readers that variables of subrange can store only certain range of values • Reliability – Assigning a value to a subrange variable that is outside the specified range is detected as an error Copyright © 2007 Addison-Wesley. All rights reserved. 1-27 Array Types • An array is an aggregate of homogeneous data elements in which an individual element is identified by its position in the aggregate, relative to the first element. • The syntax of array is fairly universal • array_name (subscript_value_list) -->element • FORTRAN, PL/I, Ada use parentheses • Most other languages use brackets Copyright © 2007 Addison-Wesley. All rights reserved. 1-28 Arrays Index (Subscript) Types • FORTRAN, C and Java: integer types only • Pascal: any ordinal type (integer, Boolean, char, enumeration) • Syntax of array declaration: var array-name = array[index-type] of array-type; • Examples: • var velocity = array [ 1..25] of real; • var day_temp = array [-10 .. 50] of real; • type color = ( red, black, blue, silver, beige); var car_color = array [color] of boolean; Copyright © 2007 Addison-Wesley. All rights reserved. 1-29 Arrays Index (Subscript) Types - continued • Pascal Index Type Examples: • var idx : array ['A'..'Z'] of string; idx['D']:='Dave'; • var a : array [‘a'..'z'] of 1..26; a[‘e']:= 5; • var schedule : array [Monday..Saturday] of string; schedule[Monday]:='Go meet clients at 10am'; • var car_price : array [Honda..Suzuki] of longint; car_price[Honda]:=15000; {US$} Copyright © 2007 Addison-Wesley. All rights reserved. 1-30 Arrays Index (Subscript) Types - continued • Ada: integer or enumeration (includes Boolean and char) • C, C++, Perl, and Fortran do not specify range checking • Java, ML, C# specify range checking • In C-based languages, the lower bound of all index ranges is fixed at 0; Fortran 95, it defaults to 1. Copyright © 2007 Addison-Wesley. All rights reserved. 1-31 Subscript Binding and Array Categories • There are 5 categories of arrays. • Static Array: statically bound and storage allocation is static (before run-time) • Arrays are static, if functions include the static specifier (in C and C++) • static int myarray[3] = {2, 3, 4}; • Advantage: Efficiency • Fixed stack-dynamic: statically bound, but the allocation is done at declaration time • Arrays are fixed stack-dynamic, if functions do not include the static specifier (in C and C++) • int myarray[3] = {2, 3, 4}; • Advantage: Space efficiency Copyright © 2007 Addison-Wesley. All rights reserved. 1-32 Subscript Binding and Array Categories - continued • Stack-dynamic: dynamically bound and the storage allocation is dynamic (done at run-time) • Ada example Get(List_Len); Declare List : array (1..List_Len) of Integer; begin … end; • Advantage: Flexibility (the size of an array need not be known until the array is to be used) Copyright © 2007 Addison-Wesley. All rights reserved. 1-33 Subscript Binding and Array Categories • Fixed heap-dynamic: dynamically bound but fixed after allocation • C, C++, C#, Fortran 95 also supports • In Java, all array are fixed heap-dynamic • C uses malloc for allocation and free deallocation • C++ uses new and delete Copyright © 2007 Addison-Wesley. All rights reserved. 1-34 Subscript Binding and Array Categories • Heap-dynamic: dynamically bound and can change any number of times • C# has a second array class, ArrayList ArrayList intList = new ArrayList (); intList.Add(nextOne); • Perl and JavaScript also support • Perl example: @list = {1, 2, 4, 7, 10); The array could be lengthened with the push function push(@list, 13, 17); Now the array’s value is (1, 2, 4, 7, 10, 13, 17). • Advantage: flexibility (arrays can grow or shrink during program execution) Copyright © 2007 Addison-Wesley. All rights reserved. 1-35 Array Initialization • Some languages allow initialization at the time of storage allocation C, C++, Java, C# example int list [] = {4, 5, 7, 83} Character strings in C and C++ char name [] = “freddie”; Arrays of strings in C and C++ char *names [] = {“Bob”, “Jake”, “Joe”]; Java initialization of String objects String[] names = {“Bob”, “Jake”, “Joe”}; Copyright © 2007 Addison-Wesley. All rights reserved. 1-36 Array Initialization - continued Fortran uses the DATA statement, and put the values in / ... / on the declaration. Integer List (3) Data List /0, 5, 5/ //List is initialized to the values Ada positions for the values can be specified: List : array (1..5) of Integer := (1, 3, 5, 7, 9); Bunch : array (1..5) of Integer:= (1 => 3, 3 => 4, others => 0); Note: the array value is (3, 0, 4, 0, 0) Copyright © 2007 Addison-Wesley. All rights reserved. 1-37 Heterogeneous Arrays • A heterogeneous array is one in which the elements need not be of the same type • Supported by Perl, Python, JavaScript, and Ruby • Python example: a = [12, 3.5, -1, ‘two’] Copyright © 2007 Addison-Wesley. All rights reserved. 1-38 Rectangular and Jagged Arrays • A rectangular array is a multi-dimensioned array in which all of the rows have the same number of elements and all columns have the same number of elements • A jagged matrix has rows with varying number of elements – Possible when multi-dimensioned arrays actually appear as arrays of arrays • C, C++, and Java support jagged arrays • Fortran, Ada support rectangular arrays • C# support both jagged and rectangular arrays Copyright © 2007 Addison-Wesley. All rights reserved. 1-39 Slices • A slice is some substructure of an array; nothing more than a referencing mechanism • Not a new data type • Slices are only useful in languages that have array operations Copyright © 2007 Addison-Wesley. All rights reserved. 1-40 Slice Examples • Fortran 95 Integer, Dimension (10) :: Vector Integer, Dimension (3, 3) :: Mat Integer, Dimension (3, 3, 4) :: Cube Vector (3:6)is a four element array Mat (:, 2)refers to the second column Mat (2:3, :)refers to the second and third row Copyright © 2007 Addison-Wesley. All rights reserved. 1-41 Slices Examples in Fortran 95 Copyright © 2007 Addison-Wesley. All rights reserved. 1-42 Record Types • A record is a possibly heterogeneous aggregate of data elements in which the individual elements are identified by names • For example: information about a student - name => character string - number => integer - grade point average =>a floating point - .... • Records are designed for this kind of need Copyright © 2007 Addison-Wesley. All rights reserved. 1-43 Definition of Records in C++ • Definition of Datatype Student record: struct student{ int roll_no; std::string name; float grade; }s1, s2, s3 • Assignment operation s1.roll_no = 1; s1.name = "Brown" Copyright © 2007 Addison-Wesley. All rights reserved. 1-44 Definition of Records in Ada • Definition of Datatype Date record: type Date is record Day: integer range (1..31); Month : Months; Year : Integer range (1..3000); end record; Copyright © 2007 Addison-Wesley. All rights reserved. 1-45 Definition of Records in COBOL • COBOL uses level numbers to show nested records; others use recursive definition 01 EMP-REC. String consisting of 02 EMP-NAME. Level 20 characters Numbers 05 FIRST PIC X(20). 05 MID PIC X(10). 05 LAST PIC X(20). 02 HOURLY-RATE PIC 99V99. Copyright © 2007 Addison-Wesley. All rights reserved. 1-46 References to Records • Record field references - Dot notation (almost all languages): record.field_name Example: Date.Month - Exception COBOL field_name OF record Example: FIRST OF EMP-NAME OF EMP-REC Copyright © 2007 Addison-Wesley. All rights reserved. 1-47 References to Records - continued • Fully qualified vs Elliptical references • Fully qualified references must include all record names • Example: • Emp_Record.Emp_Name.Middle • Elliptical references allow leaving out record names as long as the reference is unambiguous, for example in COBOL • Example: • FIRST, FIRST OF EMP-NAME, and FIRST of EMP-REC are elliptical references to the employee’s first name Copyright © 2007 Addison-Wesley. All rights reserved. 1-48 Operations on Records • Assignment is very common if the types are identical • Ada records can be initialized with aggregate literals • Date := (10, December, 1815); • COBOL provides MOVE CORRESPONDING – Copies a field of the source record to the destination record in the target record Copyright © 2007 Addison-Wesley. All rights reserved. 1-49 Operations on Records A COBOL Structure 01 INPUT-RECORD. 02 NAME. 05 FIRST PIC X(20). 05 MID PIC X(10). 05 LAST PIC X(20). 02 HOURS-WORKED PIC 99. 02 EMPLOYEE-NUMBER PIC IS 9(10). 01 OUTPUT-RECORD. 02 NAME. 05 LAST PIC X(20). 05 MID PIC X(10). 05 FIRST PIC X(20). 02 EMPLOYEE-NUMBER PIC IS 9(10). 02 GROSS-PAY PIC IS 999V99. 02 NET-PAY PIC IS 999V99. – MOVE CORRESPONDING INPUT-RECORD TO OUTPUT-RECORD. Copyright © 2007 Addison-Wesley. All rights reserved. 1-50 Evaluation and Comparison to Arrays • Records are used when collection of data values is heterogeneous • Access to array elements is much slower than access to record fields, because subscripts are dynamic (field names are static) • Record elements are not referenced by indices, but are named with identifiers Copyright © 2007 Addison-Wesley. All rights reserved. 1-51 Unions Types • Unions allow to store different data types in the same memory location. • Unions are declared and used in the same way as structures. • Like structures, it is also used to store different types of data. • Definition of Union in C++: • union union_name { data-type member-1; data-type member-2; data-type member-3; }; Copyright © 2007 Addison-Wesley. All rights reserved. 1-52 Union Example in C++ • Example: • union student { int roll_no; std::string name; float grade; } s1, s2, s3; • Assignment operation as same as struct s1.roll_no = 1; s1.name = "Brown" Copyright © 2007 Addison-Wesley. All rights reserved. 1-53 Difference between union and structure • The amount of memory required to store a structure is the sum of the memory sizes of all its members. • The memory size of a union is equal to the size of its member occupying the maximum space in the memory. Copyright © 2007 Addison-Wesley. All rights reserved. 1-54 Difference between union and structure • struct student1 { int roll_no; char name[40]; int phone_number; }; union student2 { int roll_no; char name[40]; int phone_number; }; int main() { cout << sizeof(student1) << endl; cout << sizeof(student2) << endl; } Copyright © 2007 Addison-Wesley. All rights reserved. 1-55 Difference between union and structure • Output of the example: • size of structure : 48 size of union : 40 Copyright © 2007 Addison-Wesley. All rights reserved. 1-56 Difference between union and structure • union student { int roll_no; int phone_number; char name[40]; }; int main() { student.roll_no = 1; student.phone_number = 0603021529; strcpy(student.name,"Brown"); cout << student.roll_no << endl; cout << student.phone_number << endl; cout << student.name << endl; } Copyright © 2007 Addison-Wesley. All rights reserved. 1-57 Difference between union and structure • Output of the example: • roll_no : 2003792450 phone_number : 2003792450 name : Brown • Garbage value printed for roll and phone number. Why? • we can access only one member of union at a time Copyright © 2007 Addison-Wesley. All rights reserved. 1-58 Difference between union and structure • union student { int roll_no; int phone_number; char name[40]; }; int main() { student.roll_no = 1; cout << student.roll_no << endl; strcpy(student.name,"Brown"); cout << student.name << endl; student.phone_number = 0603021529; cout << student.phone_number << endl; } Copyright © 2007 Addison-Wesley. All rights reserved. 1-59 Difference between union and structure • Output of the example: • roll_no : 1 name : Brown phone_number : 0603021529 • First, roll_no = 1 and printed it. So currently, the value of the other members is some garbage value • Second, name = "Brown", so now roll_no and phone_number contained garbage • Similarly, phone_number is printed Copyright © 2007 Addison-Wesley. All rights reserved. 1-60 Pointer and Reference Types • A pointer type variable has a range of values that consists of memory addresses and a special value, nil • Provide the power of indirect addressing • Provide a way to manage dynamic memory • A pointer can be used to access a location in the area where storage is dynamically created (usually called a heap) Copyright © 2007 Addison-Wesley. All rights reserved. 1-61 Pointer Operations • Two fundamental operations: assignment and dereferencing • Assignment is used to set a pointer variable’s value to some useful address • Dereferencing yields the value stored at the location represented by the pointer’s value Copyright © 2007 Addison-Wesley. All rights reserved. 1-62 Pointer Assignment Illustrated j = *ptr //sets j to the value located at ptr The assignment operation j = *ptr Copyright © 2007 Addison-Wesley. All rights reserved. 1-63 Pointers in C and C++ • Extremely flexible but must be used with care • Pointers can point at any variable regardless of when or where it was allocated • Asterisk (*) denotes the dereferencing operation, • Ampersand (&) denotes the operator for producing the address of a variable int *ptr; int count, init; … ptr = &init; count = *ptr; Copyright © 2007 Addison-Wesley. All rights reserved. 1-64 Pointer Arithmetic in C and C++ int list[10]; int *ptr; ptr = list; • *(ptr + 1) is equivalent to list[1] • *(ptr + index) is equivalent to list[index] • ptr[index] is equivalent to list[index]. • Pointers to arrays can be indexed as if they were array names. Copyright © 2007 Addison-Wesley. All rights reserved. 1-65 Problems with Pointers Dangling pointers (dangerous) • A pointer points to a heap-dynamic variable that has been deallocated Copyright © 2007 Addison-Wesley. All rights reserved. 1-66 Reference Types • C++ includes a special kind of pointer type called a reference type that is used primarily for formal parameters • It becomes an alternative name for an existing variable • A variable can be declared as a reference by putting ‘&’ in the declaration. int result = 0; int &ref_result = result; … ref_result = 100; result and ref_result are aliases Copyright © 2007 Addison-Wesley. All rights reserved. 1-67 Reference Types Java extends C++’s reference variables and allows them to replace pointers entirely References are references to objects, rather than being addresses C# includes both the references of Java and the pointers of C++ Pointers or references are necessary for dynamic data structures--so we can't design a language without them Copyright © 2007 Addison-Wesley. All rights reserved. 1-68 Summary • The data types of a language are a large part of what determines that language’s style and usefulness • The primitive data types of most imperative languages include numeric, character, and Boolean types • The user-defined enumeration and subrange types are convenient and add to the readability and reliability of programs • Arrays and records are included in most languages • Pointers are used for addressing flexibility and to control dynamic storage management Copyright © 2007 Addison-Wesley. All rights reserved. 1-69 Chapter 7 Expressions and Assignment Statements ISBN 0-321-49362-1 Chapter 7 Topics • • • • • • • Introduction Arithmetic Expressions Type Conversions Relational and Boolean Expressions Short-Circuit Evaluation Assignment Statements Mixed-Mode Assignment Copyright © 2007 Addison-Wesley. All rights reserved. 1-2 Introduction • Expressions are the fundamental means of specifying computations in a programming language • To understand expression evaluation, need to be familiar with the orders of operator and operand evaluation • The operator evaluation order is dictated by associativity and precedence • Essence of imperative languages is dominant role of assignment statements Copyright © 2007 Addison-Wesley. All rights reserved. 1-3 Arithmetic Expressions • Arithmetic evaluation was one of the motivations for the development of the first programming languages • Arithmetic expressions consist of operators, operands, parentheses, and function calls Copyright © 2007 Addison-Wesley. All rights reserved. 1-4 Arithmetic Expressions: Design Issues • Design issues for arithmetic expressions – – – – – Operator precedence rules? Operator associativity rules? Order of operand evaluation? Operand evaluation side effects? Type mixing in expressions? Copyright © 2007 Addison-Wesley. All rights reserved. 1-5 Arithmetic Expressions: Operators • A unary operator has one operand • A binary operator has two operands – Binary operators are infix • A ternary operator has three operands – The first is a comparison argument – The second is the result upon a true comparison – The third is the result upon a false comparison Copyright © 2007 Addison-Wesley. All rights reserved. 1-6 Arithmetic Expressions: Operator Precedence Rules • The operator precedence rules for expression evaluation define the order in which “adjacent” operators of different precedence levels are evaluated • Typical precedence levels – – – – parentheses ** (if the language supports it) *, / +, - Copyright © 2007 Addison-Wesley. All rights reserved. 1-7 Arithmetic Expressions: Operator Associativity Rule • The operator associativity rules for expression evaluation define the order in which adjacent operators with the same precedence level are evaluated • Typical associativity rules – Left to right, except **, which is right to left • Ada is nonassociative • APL is different; all operators have equal precedence and all operators associate right to left • Precedence and associativity rules can be overriden with parentheses Copyright © 2007 Addison-Wesley. All rights reserved. 1-8 Arithmetic Expressions: Conditional Expressions • Conditional Expressions – if-then-else statement if (count == 0) average = 0 else average = sum /count – C-based languages (e.g., C, C++) Copyright © 2007 Addison-Wesley. All rights reserved. 1-9 Arithmetic Expressions: Conditional Expressions • Conditional Expressions – C-based languages (e.g., C, C++) if else – Conditional expression statement: average = (count == 0)? 0 : sum / count Copyright © 2007 Addison-Wesley. All rights reserved. 1-10 Arithmetic Expressions: Nested Conditional Expresiosns • Ternary operators can be nested just like if-else statements. Consider the following C code: int a = 1, b = 2, ans; if (a == 1) { if (b == 2) { ans = 3; } else ans = 5; }else ans = 0; printf ("%d\n", ans); • The same code using a nested ternary operator: int a = 1, b = 2, ans; ans = (a == 1 ? (b == 2 ? 3 : 5) : 0); printf ("%d\n", ans); Copyright © 2007 Addison-Wesley. All rights reserved. 1-11 Arithmetic Expressions: Operand Evaluation Order • Operand evaluation order 1. Variables: fetch the value from memory 2. Parenthesized expressions: evaluate all operands and operators first 3. The most interesting case is when an operand is a function call Copyright © 2007 Addison-Wesley. All rights reserved. 1-12 Arithmetic Expressions: Potentials for Side Effects • Functional side effects: when a function changes a two-way parameter or a non-local variable • Problem with functional side effects: – When a function referenced in an expression alters another operand of the expression; e.g., for a parameter change: a = 10; /* assume that fun changes its parameter */ b = a + fun(a); Copyright © 2007 Addison-Wesley. All rights reserved. 1-13 Arithmetic Expressions: Potentials for Side Effects • Illustration of same problem with C program int a = 5; int fun1(int n){ n = 17; return 3; }/*of fun1 */ void main(){ a = a + fun1(a); } /*of main*/ Copyright © 2007 Addison-Wesley. All rights reserved. 1-14 Arithmetic Expressions: Potentials for Side Effects • void main (){ int z = 12; void g(){ int x = 3; int y = 4; void f(){ z = x + y; } void h(){ int z = 3; int y = 2; f(); } f(); } g(); 1-15 Arithmetic Expressions: Potentials for Side Effects int fun(int *k){ *k += 4; return 3 * (*k) - 1; } void main(){ int i = 10, j = 10, sum1, sum2; sum1 = (i / 2) + fun(&i); sum2 = fun(&j) + (j / 2); printf("sum1=%d " "sum2=%d", sum1,sum2); } • Output: sum1=46 sum2=48 Copyright © 2007 Addison-Wesley. All rights reserved. 1-16 Functional Side Effects • Two possible solutions to the problem 1. Write the language definition to disallow functional side effects • No two-way parameters in functions • No non-local references in functions • Advantage: it works! • Disadvantage: inflexibility of one-way parameters and lack of non-local references 2. Write the language definition to demand that operand evaluation order be fixed • Disadvantage: limits some compiler optimizations • Java requires that operands appear to be evaluated in left-to-right order Copyright © 2007 Addison-Wesley. All rights reserved. 1-17 Type Conversions • A narrowing conversion is one that converts an object to a type that cannot include all of the values of the original type e.g., float to int • A widening conversion is one in which an object is converted to a type that can include at least approximations to all of the values of the original type e.g., int to float Copyright © 2007 Addison-Wesley. All rights reserved. 1-18 Type Conversions - continued • Widening conversions in Java – – – – – – byte to short, int, long, float, or double short to int, long, float, or double char to int, long, float, or double int to long, float, or double long to float, or double float to double • Narrowing conversions in Java – – – – – – short to byte or char char to byte or short int to byte, short, or char long to byte, short, char, or int float to byte, short, char, int, or long double to byte, short, char, int, long, or float 1-19 Type Conversions: Mixed Mode • A mixed-mode expression is one that has operands of different types • A coercion is an implicit type conversion • Disadvantage of coercions: – They decrease in the type error detection ability of the compiler • Ex: int a; float b, c, d; … d = b * a; Copyright © 2007 Addison-Wesley. All rights reserved. 1-20 Type Conversions: Mixed Mode • In Ada, there are virtually no coercions in expressions A : Integer; B, C, D: Float; … D:= B * A; Copyright © 2007 Addison-Wesley. All rights reserved. 1-21 Type Conversions: Mixed Mode • In most languages, all numeric types are coerced in expressions, using widening conversions byte a, b, c … a = b + c; Copyright © 2007 Addison-Wesley. All rights reserved. 1-22 Explicit Type Conversions • Called casting in C-based languages • Examples – C: (int)angle – Ada: Float (Sum) Copyright © 2007 Addison-Wesley. All rights reserved. 1-23 Relational and Boolean Expressions • Relational Expressions – Use relational operators and operands of various types – Evaluate to some Boolean representation – Operator symbols used vary somewhat among languages (!=, /=, .NE., <>) • JavaScript and PHP have two additional relational operator, === and !== – Similar to their cousins, == and !=, except that they do not coerce their operands • Relational operators always have lower precedence than the arithmetic operators – a + 1 > 2 * b Copyright © 2007 Addison-Wesley. All rights reserved. 1-24 Relational and Boolean Expressions • Boolean Expressions – Operands are Boolean and the result is Boolean – Example operators FORTRAN 77 FORTRAN 90 C Ada .AND. .OR. .NOT. and or not && || ! and or not • Boolean operators have lower precedence than relational operators Copyright © 2007 Addison-Wesley. All rights reserved. 1-25 Relational and Boolean Expressions: No Boolean Type in C • C89 has no Boolean type--it uses int type with 0 for false and nonzero for true • One odd characteristic of C’s expressions: a < b < c is a legal expression, but the result is not what you might expect: – Left operator is evaluated, producing 0 or 1 – The evaluation result is then compared with the third operand (i.e., c) Copyright © 2007 Addison-Wesley. All rights reserved. 1-26 Relational and Boolean Expressions: No Boolean Type in C • Python Example for a<b<c: a, b, c = 3, 1, 2 if a < b < c: print "increasing" else: print "not increasing“ Output: not increasing Copyright © 2007 Addison-Wesley. All rights reserved. 1-27 Relational and Boolean Expressions: No Boolean Type in C • C Example for a<b<c: int a = 3, b = 1, c = 2; if a < b < c: print "increasing" else: print "not increasing“ Output: increasing Copyright © 2007 Addison-Wesley. All rights reserved. 1-28 Short Circuit Evaluation • An expression in which the result is determined without evaluating all of the operands and/or operators • Example: (13*a) * (b/13–1) If a is zero, there is no need to evaluate (b/13-1) • The value of the boolean expression (a >= 0) && (b < 10) If a < 0, there is no need to evaluate (b < 10) Copyright © 2007 Addison-Wesley. All rights reserved. 1-29 Short Circuit Evaluation • Problem with non-short-circuit evaluation index = 0; while (index < length) && (LIST[index] != key) index++; – When index=length, LIST [index] will cause an indexing error (assuming LIST, length -1 is upperbound) Copyright © 2007 Addison-Wesley. All rights reserved. 1-30 Assignment Statements • The general syntax <target_var> <assign_operator> <expression> • The assignment operator = FORTRAN, BASIC, the C-based languages := ALGOLs, Pascal, Ada • = can be bad when it is overloaded for the relational operator for equality (that’s why the C-based languages use == as the relational operator) Copyright © 2007 Addison-Wesley. All rights reserved. 1-31 Assignment Statements: Conditional Targets • Conditional targets (Perl) ($flag ? $total : $subtotal) = 0 Which is equivalent to if ($flag){ $total = 0 } else { $subtotal = 0 } Copyright © 2007 Addison-Wesley. All rights reserved. 1-32 Assignment Statements: Compound Operators • A shorthand method of specifying a commonly needed form of assignment • Introduced in ALGOL; adopted by C • Example a = a + b is written as a += b Copyright © 2007 Addison-Wesley. All rights reserved. 1-33 Assignment Statements: Unary Operators • Unary assignment operators in C-based languages combine increment and decrement operations with assignment • Examples count = count +1; sum = ++count equivalent to sum = count; sum = count; sum = count++ equivalent to count = count +1; count++ (count incremented) -count++ (count incremented then negated – when two unary operators apply to the same operand, the association is right to left. ) Copyright © 2007 Addison-Wesley. All rights reserved. 1-34 Assignment as an Expression • In C-based languages, Perl and JavaScript, the assignment statement produces a result and can be used as operands • An example: while ((ch = getchar())!= EOF){…} ch = getchar() is carried out; the result (assigned to ch) is used as a conditional value for the while statement Copyright © 2007 Addison-Wesley. All rights reserved. 1-35 List Assignments • Perl and Ruby support list assignments e.g., ($first, $second, $third) = (20, 30, 40); • Interchanging of two variables e.g., ($first, $second) = ($second, $first); Copyright © 2007 Addison-Wesley. All rights reserved. 1-36 Mixed-Mode Assignment • Assignment statements can also be mixed-mode, for example int a, b; float c; c = a / b; • In Fortran, C, and C++, any numeric type value can be assigned to any numeric type variable • In Java, only widening assignment coercions are done • In Ada, there is no assignment coercion Copyright © 2007 Addison-Wesley. All rights reserved. 1-37 Summary • • • • Expressions Operator precedence and associativity Mixed-type expressions Various forms of assignment Copyright © 2007 Addison-Wesley. All rights reserved. 1-38 Chapter 8 Statement-Level Control Structures ISBN 0-321-49362-1 Chapter 8 Topics • Introduction • Selection Statements – Two-Way Selection Statements – Multiple-Way Selection Statements • Iterative Statements – Counter-Controlled Loops – Logically-Controlled Loops Copyright © 2007 Addison-Wesley. All rights reserved. 1-2 Levels of Control Flow – Within expressions (Chapter 7) – Among program units – Among program statements (this chapter) Copyright © 2007 Addison-Wesley. All rights reserved. 1-3 Control Statements: Evolution • FORTRAN I control statements were based directly on IBM 704 hardware • Much research and argument in the 1960s about the issue – One important result: It was proven that all algorithms represented by flowcharts can be coded with only two-way selection and pretest logical loops Copyright © 2007 Addison-Wesley. All rights reserved. 1-4 Selection Statements • A selection statement provides the means of choosing between two or more paths of execution • Two general categories: – Two-way selectors – Multiple-way selectors Copyright © 2007 Addison-Wesley. All rights reserved. 1-5 Two-Way Selection Statements • General form: if control_expression then clause else clause • Design Issues: – What is the form and type of the control expression? – How are the then and else clauses specified? – How should the meaning of nested selectors be specified? Copyright © 2007 Addison-Wesley. All rights reserved. 1-6 The Control Expression • If the then reserved word or some other syntactic marker is not used to introduce the then clause, the control expression is placed in parentheses • In C89, C99, Python, and C++, the control expression can be arithmetic • In languages such as Ada, Java, Ruby, and C#, the control expression must be Boolean Copyright © 2007 Addison-Wesley. All rights reserved. 1-7 Clause Form • In many contemporary languages, the then and else clauses can be single statements or compound statements • In Perl, all clauses must be delimited by braces (they must be compound) • Python uses indentation to define clauses if x > y : x = y print "case 1" Copyright © 2007 Addison-Wesley. All rights reserved. 1-8 Nesting Selectors • Java example if (sum == 0) if (count == 0) result = 0; else result = 1; • Which if gets the else? • Java's static semantics rule: else matches with the nearest if Copyright © 2007 Addison-Wesley. All rights reserved. 1-9 Nesting Selectors (continued) • To force an alternative semantics, compound statements may be used: if (sum == 0) { if (count == 0) result = 0; } else result = 1; • The above solution is used in C, C++, and C# • Perl requires that all then and else clauses to be compound Copyright © 2007 Addison-Wesley. All rights reserved. 1-10 Nesting Selectors (continued) In Perl, the previous code would be written if (sum == 0) { if (sum == 0) { if (count == 0){ result = 0; } else { result = 1; } if (count == 0){ result = 0; } } else { result = 1; } • Else is matched to outer if Copyright © 2007 Addison-Wesley. All rights reserved. • } Else is matched to inner if 1-11 Nesting Selectors (continued) • Statement sequences as clauses: Ruby if sum == 0 then if count == 0 then result = 0 else result = 1 end end if sum == 0 then if count == 0 then result = 0 end else result = 1 end • else is matched to inner if • Copyright © 2007 Addison-Wesley. All rights reserved. else is matched to outer if 1-12 Nesting Selectors (continued) • Python if sum == 0 : if count == 0 : result = 0 else : result = 1 • else is matched to inner if Copyright © 2007 Addison-Wesley. All rights reserved. if sum == 0 : if count == 0 : result = 0 else : result = 1 • else is matched to outer if 1-13 Multiple-Way Selection Statements • • Allow the selection of one of any number of statements or statement groups Design Issues: 1. 2. 3. 4. What is the form and type of the control expression? How are the selectable segments specified? How are case values specified? What is done about unrepresented expression values? Copyright © 2007 Addison-Wesley. All rights reserved. 1-14 Multiple-Way Selection: Syntax • C, C++, and Java switch (expression) { case const_expr_1: stmt_1; … case const_expr_n: stmt_n; [default: stmt_n+1;] } Copyright © 2007 Addison-Wesley. All rights reserved. 1-15 Multiple-Way Selection: C Example • Design choices for C’s switch statement 1. Control expression and constant expressions can be only an integer type 2. Selectable segments can be statement sequences, blocks, or compound statements 3. Any number of segments can be executed in one execution of the construct (it doesn’t have to be implicit branch at the end of selectable segments) 4. default clause is for unrepresented values (if there is no default, the whole statement does nothing) Copyright © 2007 Addison-Wesley. All rights reserved. 1-16 Multiple-Way Selection: C Example • int num = 8; switch (num){ case 7: printf("Value is 7"); break; case 8: printf("Value is 8"); break; case 9: printf("Value is 9"); break; default: printf("Out of range"); break; } 1-17 Multiple-Way Selection: C# Example • C# - Differs from C in that it has a static semantics rule that disallows the implicit execution of more than one segment - Each selectable segment must end with an unconditional branch (goto or break) Copyright © 2007 Addison-Wesley. All rights reserved. 1-18 Multiple-Way Selection: C# Example • switch (value){ case -1; Negatives++; break; case 0; Zeros++; goto case 1; case 1; Positives++; break; default: Console.Writeline(“Error in switch \n”); Copyright © 2007 Addison-Wesley. All rights reserved. 1-19 Multiple-Way Selection: Ada Example • case expression is when choice list1 => stmt_sequence1; … when choice list2 => stmt_sequence2; [when others => stmt_sequence3;] end case; • More reliable than C’s switch (once a stmt_sequence execution is completed, control is passed to the first statement after the case statement) Copyright © 2007 Addison-Wesley. All rights reserved. 1-20 Multiple-Way Selection: Ada Example • Ada Segments design choices: 1. Expression can be any ordinal type 2. Segments can be single or compound 3. Only one segment can be executed per execution of the construct • Constant List Forms: 1. A list of constants 2. Can include: - Subranges - Boolean OR operators (|) Copyright © 2007 Addison-Wesley. All rights reserved. 1-21 Multiple-Way Selection: Ruby Example • case expression when value1 then stmt_sequence1 … when value2 then stmt_sequence2 [else stmt_sequence3] end • case when when when else end in_val -1 then neg_count++ 0 then zero_count++ 1 then pos_count++ puts “Error – in_val is out of range” Copyright © 2007 Addison-Wesley. All rights reserved. 1-22 Multiple-Way Selection Using if Multiple Selectors can appear as direct extensions to two-way selectors, using else-if clauses, for example in Python: if count < 10 : if count < 10 : bag1 = True elif count < 100 : bag2 = True elif count < 1000 : bag3 = True bag1 = True else : if count < 100 : bag2 = True else : if count < 1000 : bag3 = True else : bag4 = True Which is equivalent to this code Copyright © 2007 Addison-Wesley. All rights reserved. 1-23 Multiple-Way Selection Using if • The Python example can be written as a Ruby case case when count < 10 then bag1 = True when count < 100 then bag2 = True when count < 1000 then bag3 = True end Copyright © 2007 Addison-Wesley. All rights reserved. 1-24 Iterative Statements • The repeated execution of a statement or compound statement is accomplished either by iteration or recursion • There are two types of Iterative Statements – Counter-Controlled Loops – Logically-Controlled Loops • Control mechanism in the loop may be at at the top of the loop or at the bottom of the loop Copyright © 2007 Addison-Wesley. All rights reserved. 1-25 Counter-Controlled Loops • A counting iterative statement has a loop variable, and a means of specifying the initial and terminal, and stepsize values • Design Issues: 1. What are the type and scope of the loop variable? 2. What is the value of the loop variable at loop termination? 3. Should it be legal for the loop variable or loop parameters to be changed in the loop body, and if so, does the change affect loop control? 4. Should the loop parameters be evaluated only or once for every iteration? Copyright © once, 2007 Addison-Wesley. All rights reserved. 1-26 Counter-Controlled Loops: Examples • FORTRAN 95 syntax : first form DO label var = start, finish [, stepsize] • Stepsize can be any value but not zero • Parameters can be expressions • Design choices: 1. Loop variable must be INTEGER 2. Loop variable always has its last value 3. The loop variable cannot be changed in the loop, but the parameters can; because they are evaluated only once, it does not affect loop control 4. Loop parameters are evaluated only once Copyright © 2007 Addison-Wesley. All rights reserved. 1-27 Counter-Controlled Loops: Examples • Example for first form – Do 10 index = 1, 30 … 10 continue • FORTRAN 95 : a second form: [name:] Do variable = initial, terminal [,stepsize] … End Do [name] • Example for second form – Do count = 1, n … End Do Copyright © 2007 Addison-Wesley. All rights reserved. 1-28 Counter-Controlled Loops: Examples • C-based languages for ([expr_1] ; [expr_2] ; [expr_3]) statement – First expression is for initialization – Second expression is the loop control (If the second expression is absent, it is an infinite loop) – Third expression is executed after each execution of the loop body (often increment loop counter) • Design choices: - Everything can be changed in the loop - The first expression is evaluated once, but the other two are evaluated with each iteration Copyright © 2007 Addison-Wesley. All rights reserved. 1-29 Counter-Controlled Loops: Examples • A skeletal C for Construct for (count = 1; count <= 10; count++) … • for (count1 = 0, count2 = 1.0; count1 <= 10 && count2 <= 100.0; sum = ++count1 + count2, count2 *= 2.5); – The resulting value is not used in the loop control. Copyright © 2007 Addison-Wesley. All rights reserved. 1-30 Counter-Controlled Loops: Examples • C++ differs from C in two ways: 1. The control expression can also be Boolean 2. The initial expression can include variable definitions (scope is from the definition to the end of the loop body) • Java and C# – Differs from C++ in that the control expression must be Boolean Copyright © 2007 Addison-Wesley. All rights reserved. 1-31 Counter-Controlled Loops: Examples • Python Syntax for loop_variable in object: - loop body [else: - else clause] - The object is often a range, which is either a list of values in brackets ([2, 4, 6]), or a call to the range function (range(5), which returns 0, 1, 2, 3, 4 - The loop variable takes on the values specified in the given range, one for each iteration - The else clause, which is optional, is executed if the loop terminates normally Copyright © 2007 Addison-Wesley. All rights reserved. 1-32 Counter-Controlled Loops: Examples • Python Syntax for loop_variable in object: - loop body [else: - else clause] - for count in [2, 4, 6]: print count Output = 2 4 6 Copyright © 2007 Addison-Wesley. All rights reserved. 1-33 Counter-Controlled Loops: Examples • Python • For simple counting loops range function is used. – range(5) returns [0, 1, 2, 3, 4] – range(2, 7) returns [2, 3, 4, 5, 6] – range(0, 8, 2) returns [0, 2, 4, 6] - for count in range(5, 15, 3): print count Output = 5 8 11 14 1-34 Iterative Statements: LogicallyControlled Loops • Repetition control is based on a Boolean expression • Design issues: – Control pretest or posttest? – Should the logically controlled loop be a special case of the counting loop statement or a separate statement? Copyright © 2007 Addison-Wesley. All rights reserved. 1-35 Logically-Controlled Loops: Examples • C, C++, C# have both pretest and posttest forms, in which the control expression can be arithmetic: • while(ctrl_expr){ loop body } • do{ loop body } while (ctrl_expr) • Java is like C and C++, except the control expression must be Boolean (and the body can only be entered at the beginning Copyright © 2007 Addison-Wesley. All rights reserved. 1-36 Logically-Controlled Loops: Examples • Ada has a pretest version, but no posttest • Perl and Ruby have two pretest logical loops, while and until. • Perl also has two posttest loops, which use while and until as statement modifiers on do blocks Copyright © 2007 Addison-Wesley. All rights reserved. 1-37 Logically-Controlled Loops: Examples • Perl Example • my $counter = 5; until($counter == 0){ print("$counter \n"); $counter--; } • Output = 5 4 3 2 1 Copyright © 2007 Addison-Wesley. All rights reserved. 1-38 Iterative Statements: User-Located Loop Control Mechanisms • Sometimes it is convenient for the programmers to decide a location for loop control (other than top or bottom of the loop) • Simple design for single loops (e.g., break) • Design issue for nested loops 1. Should control be transferable out of more than one loop? Copyright © 2007 Addison-Wesley. All rights reserved. 1-39 Iterative Statements: User-Located Loop Control Mechanisms break • C , C++, Python, Ruby, and C# have unconditional unlabeled exits (break) • Java and Perl can have unconditional labeled exits (break in Java, last in Perl) Copyright © 2007 Addison-Wesley. All rights reserved. 1-40 Logically-Controlled Loops: break Example • Java Example • outerloop: for (int i=0; i < 5; i++){ for (int j=0; j < 5; j++){ if (i * j > 6){ break outerloop; } System.out.println(i + " " + j); } } Copyright © 2007 Addison-Wesley. All rights reserved. 1-41 Iterative Statements: User-Located Loop Control Mechanisms continue • C, C++, and Python have an unlabeled control statement, continue, that skips the remainder of the current iteration, but does not exit the loop • Java and Perl have labeled versions of continue Copyright © 2007 Addison-Wesley. All rights reserved. 1-42 Logically-Controlled Loops: continue Example • Python Example for val in "string": if val == "i": continue print(val) print("The end") • Output: s t r n g The end Copyright © 2007 Addison-Wesley. All rights reserved. 1-43 Chapter 15 Functional Programming Languages ISBN 0-321-49362-1 Chapter 15 Topics • • • • • • • • • • Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming Language: LISP Introduction to Scheme COMMON LISP ML Haskell Applications of Functional Languages Comparison of Functional and Imperative Languages Copyright © 2007 Addison-Wesley. All rights reserved. 1-2 Introduction • The design of the imperative languages is based directly on the von Neumann architecture – Efficiency is the primary concern, rather than the suitability of the language for software development • The design of the functional languages is based on mathematical functions • Backus: “Functioanal Programming Languages are better than imperative languages because they result in programs are more readable, more reliable, and more likely to be correct.” Copyright © 2007 Addison-Wesley. All rights reserved. 1-3 Functional Programming Languages • • • • • LISP Scheme COMMON LISP ML Haskell Copyright © 2007 Addison-Wesley. All rights reserved. 1-4 Mathematical Functions • A mathematical function can be represented by: Copyright © 2007 Addison-Wesley. All rights reserved. 1-5 Mathematical Functions • A mathematical function is a mapping of members of one set, called the domain set, to another set, called the range set • A mapping is described by an expression • A function returns an element of the range set. Copyright © 2007 Addison-Wesley. All rights reserved. 1-6 Lambda Expressions • A simple function – cube (x) x * x * x • Lambda notation is for nameless functions • A lambda expression specifies the parameter(s) and the mapping of a function in the following form – (x) (x * x * x) for the function cube (x) • Lambda expressions, like other function definitions, can have more than one parameter – (x y) (x * y) Copyright © 2007 Addison-Wesley. All rights reserved. 1-7 Functional Forms • A higher-order function, or functional form, is one that either takes functions as parameters or yields a function as its result, or both Copyright © 2007 Addison-Wesley. All rights reserved. 1-8 Function Composition • A functional form that takes two functions as parameters and yields a function whose value is the first actual parameter function applied to the application of the second Form: h f ° g which means h (x) f ( g (x)) For f (x) x + 2 and g (x) 3 * x, h f ° g yields (3 * x)+ 2 Copyright © 2007 Addison-Wesley. All rights reserved. 1-9 Apply-to-all • A functional form that takes a single function as a parameter and yields a list of values obtained by applying the given function to each element of a list of parameters Form: For h (x) x * x ( h, (2, 3, 4)) yields (4, 9, 16) Copyright © 2007 Addison-Wesley. All rights reserved. 1-10 Fundamentals of Functional Programming Languages • The objective of the design of a FPL is to mimic mathematical functions to the greatest extent possible • The basic process of computation is fundamentally different in a FPL than in an imperative language – In an imperative language, operations are done and the results are stored in variables for later use – Management of variables is a constant concern and source of complexity for imperative programming • In an FPL, variables are not necessary, as is the case in mathematics Copyright © 2007 Addison-Wesley. All rights reserved. 1-11 Referential Transparency • In an FPL, the evaluation of a function always produces the same result given the same parameters – We can replace x = 2 + (3 * 4) with x = 2 + 12 or x = 2 + (2 * 6) Copyright © 2007 Addison-Wesley. All rights reserved. 1-12 LISP Data Types and Structures • Data object types: originally only atoms and lists • List form: parenthesized collections of sublists and/or atoms e.g., (A B C D)or(A B (C D) E) • Originally, LISP was a typeless language • LISP lists are stored internally as singlelinked lists Copyright © 2007 Addison-Wesley. All rights reserved. 1-13 LISP Data Types and Structures Copyright © 2007 Addison-Wesley. All rights reserved. 1-14 LISP Lists Representation Examples • (1 (2 (3 4))) • (((1 2) 3) 4 (5 6)) Copyright © 2007 Addison-Wesley. All rights reserved. 1-15 Origins of Scheme • A mid-1970s dialect of LISP, designed to be a cleaner, more modern, and simpler version than the contemporary dialects of LISP • Uses only static scoping • Functions are first-class entities – They can be the values of expressions and elements of lists – They can be assigned to variables and passed as parameters Copyright © 2007 Addison-Wesley. All rights reserved. 1-16 Evaluation of Interpeter • • • • • • • Scheme interpreter is a read-evaluate-write infinite loop Expressions are interpreted by the function EVAL Literals evaluate to themselves First, parameters are evaluated, in no particular order The values of the parameters are substituted into the function body The function body is evaluated The value of the last expression in the body is the value of the function Copyright © 2007 Addison-Wesley. All rights reserved. 1-17 Oline Scheme Interpreter • https://www.tutorialspoint.com/execute_sc heme_online.php Copyright © 2007 Addison-Wesley. All rights reserved. 1-18 Output Functions • (DISPLAY expression) • (NEWLINE) Copyright © 2007 Addison-Wesley. All rights reserved. 1-19 Primitive Functions • Arithmetic: +, -, *, /,SQRT, REMAINDER, MODULO, MIN, MAX Expression Value 42 42 (* 3 7) 21 (+ 5 7 8) 20 (- 5 6 ) -1 (- 15 7 2) 6 (- 24 (* 4 3)) 12 Copyright © 2007 Addison-Wesley. All rights reserved. 1-20 Function Definition: LAMBDA • Lambda Expressions – Form is based on notation e.g., (LAMBDA (x) (* x x)) x is called a bound variable • Lambda expressions can be applied e.g., ((LAMBDA (x) (* x x)) 7) this function yields 49 Copyright © 2007 Addison-Wesley. All rights reserved. 1-21 Special Form Function: DEFINE • A Function for Constructing Functions DEFINE Two forms: 1. To bind a name to a value (DEFINE symbol expression) e.g., (DEFINE pi 3.141593) Example use: (DEFINE two_pi (* 2 pi)) 2. To bind a name to a lambda expression (DEFINE (function_name parameters)(expr)) e.g., (DEFINE (square x) (* x x)) Example use: (square 5) It yields 25 Copyright © 2007 Addison-Wesley. All rights reserved. 1-22 Special Form Function: DEFINE • The evaluation process for DEFINE is different! The first parameter is never evaluated. The second parameter is evaluated and bound to the first parameter - e.g: (DEFINE x 10) (DEFINE x (+ 3 4)) - the leghth of the hypotenuse of a right triangle (DEFINE (hypotenuse side1 side2) (sqrt(+(square side1)(square side2))) ) (DEFINE (square number)(* number number)) Copyright © 2007 Addison-Wesley. All rights reserved. 1-23 DEFINE Examples • Conversion function from celcius to fahrenheit (define (celsius->fahrenheit celsius) (+ (* 1.8 celsius) 32) (display (celsius->fahrenheit 0)) Output: 32 (display (celsius->fahrenheit 100)) Output: 212 Copyright © 2007 Addison-Wesley. All rights reserved. 1-24 Numeric Predicate Functions • #T is true and #F is false (sometimes () is used for false) Copyright © 2007 Addison-Wesley. All rights reserved. 1-25 Control Flow: IF • Selection- the special form, IF (IF predicate then_exp else_exp) • e.g. Factorial – Mathematical induction of factorial fac(n) = { 1 { n*fac(n-1) n=0 n>0 – Scheme code of factorial (DEFINE (factorial n) (IF (= n 0) 1 (* n (factorial (- n 1)))) ) Copyright © 2007 Addison-Wesley. All rights reserved. 1-26 Tracing factorial • Tracing (by hand) a call to length: – Call: (factorial n) – Trace: (factorial 5) (* 4 (factorial (- 4 1))) (* 4 (* 3 (factorial (- 3 1)))) (* 4 (* 3 (* 2 (factorial (- 2 1))))) (* 4 (* 3 (* 2 (* 1 (factorial (- 1 1)))))) (* 4 (* 3 (* 2 (* 1 1)))) (* 4 (* 3 (* 2 1))) (* 4 (* 3 2)) (* 4 6) 24 Copyright © 2007 Addison-Wesley. All rights reserved. 1-27 Control Flow: COND • Multiple Selection - the special form, COND General form: (COND (predicate_1 expr ) (predicate_2 expr ) ... (predicate_n expr ) (ELSE expr )) • The predicates of the parameters are evaluated one at a time, in order from the first, until one evaluates to true Copyright © 2007 Addison-Wesley. All rights reserved. 1-28 Example of COND (DEFINE (compare x y) (COND ((> x y) “x is greater than y”) ((< x y) “y is greater than x”) (ELSE “x and y are equal”) ) ) Copyright © 2007 Addison-Wesley. All rights reserved. 1-29 Example of COND for leap year • A year is a leap year if it's divisible by 400, or if it's divisible by 4 but not by 100 (DEFINE (leap? year) (COND ((ZERO? (MODULO year 400)) #T) ((ZERO? (MODULO year 100)) #F) (ELSE (ZERO? (MODULO year 4))) )) Copyright © 2007 Addison-Wesley. All rights reserved. 1-30 Second Way for Leap Year Without COND (define (leap? year) (or (and (zero? (modulo year 4)) (not (zero? (modulo year 100)))) (zero? (modulo year 400))) ) Copyright © 2007 Addison-Wesley. All rights reserved. 1-31 List Functions: QUOTE • QUOTE is a pointer. • QUOTE can be abbreviated with the apostrophe prefix operator – '(A B) is equivalent to (QUOTE (A B)) • E.g. – (‘A) returns A – (‘(A B C)) returns (A B C) – (DEFINE foo (‘(1 2 3))) (This expr. defines foo, and initializes its binding with a pointer to a three-element list.) Copyright © 2007 Addison-Wesley. All rights reserved. 1-32 List Functions: CONS • CONS builts a list from its two arguments, the first one is either an atom or a list; the second is a list. e.g.,(CONS ‘A ‘()) returns (A) (CONS 'A '(B C)) returns (A B C) (CONS ‘() '(A B)) returns (() A B) (CONS ‘(A B) '(C D)) returns ((A B)C D) Copyright © 2007 Addison-Wesley. All rights reserved. 1-33 CONS Representation Copyright © 2007 Addison-Wesley. All rights reserved. 1-34 List Functions: LIST • LIST takes any number of parameters; returns a list with the parameters as elements e.g., (LIST ‘apple ‘orange ‘grape) returns (apple orange grape) Copyright © 2007 Addison-Wesley. All rights reserved. 1-35 List Functions: CAR • CAR takes a list parameter; returns the first element of that list e.g., (CAR '(A B C))returns A (CAR '((A B) C D)) returns (A B) (CAR ‘A)is an error because A is not a list (CAR '(A)) returns A (CAR '()) is an error Copyright © 2007 Addison-Wesley. All rights reserved. 1-36 List Functions: CDR • CDR takes a list parameter; returns the list after removing its first element e.g., (CDR '(A B C)) returns(B C) (CDR '((A B) C D)) returns(C D) (CDR ‘A) is an error. (CDR '(A)) returns () (CDR '()) is an error. Copyright © 2007 Addison-Wesley. All rights reserved. 1-37 Scheme Functional Forms • Functional Composition – (CAR (B) – (CDR (C) – (CAR (A) – (CDR (B C) – (CONS (A B) (CDR '(A B C)) returns? (CDR '(A B C))) returns? (CAR '((A B) B C))) returns? (CAR '((A B C) D))) returns? (CAR '(A B))(CDR ‘(A B))) returns? Copyright © 2007 Addison-Wesley. All rights reserved. 1-38 A CAR and CDR Example • Input: one parameter which is a list of numbers. • Output: the sum of all the numbers in the list. • Example: ‘(2 3 4) returns 9 (define (sum-list ls) (cond ((null? ls) 0) (else (+ (car ls)(sum-list (cdr ls)))) ) ) Copyright © 2007 Addison-Wesley. All rights reserved. 1-39 Predicate Functions: EQ? • There are 3 predicate functions EQ?, NULL?, LIST? • EQ? takes two parameters; it returns #T if both parameters are atoms and the two are the same e.g., (EQ? 'A 'A) yields #T (EQ? 'A 'B) yields #F (EQ? ‘(A B) ‘(A B)) yields #F or #T – Note that if EQ? is called with list parameters, the result is not reliable Copyright © 2007 Addison-Wesley. All rights reserved. 1-40 Predicate Functions: LIST? and NULL? • LIST? takes one parameter; it returns #T if the parameter is a list; otherwise #F e.g: (LIST? ‘(X Y))returns #T (LIST? ‘X)returns #F (LIST? ‘())returns #T • NULL? takes one parameter; it returns #T if the parameter is the empty list; otherwise#F e.g: (NULL? ‘(A B))returns #F (NULL? ‘())returns #T (NULL? ‘A)returns #F (NULL? ‘(()))returns #F Copyright © 2007 Addison-Wesley. All rights reserved. 1-41 A Scheme Function Example: member? • Function name: member? • Input: takes 2 parameters which are an atom and a simple list; • Output: returns #T if the atom is in the list; #F otherwise • Example: (member? 'B '(A B C)) returns #T (member? 'B '(A C D E)) returns #F DEFINE (member? atm lis) (COND ((NULL? lis) #F) ((EQ? atm (CAR lis)) #T) (ELSE (member? atm (CDR lis))) )) Copyright © 2007 Addison-Wesley. All rights reserved. 1-42 A Scheme Function Example: equalsimp? • Function name: equalsimp? • Input: takes 2 parameters which are simple lists; • Output: returns #T if the two simple lists are equal; #F otherwise • Example: (equalsimp? ‘(A B C) '(A B C)) returns #T (equalsimp? ‘(B) '(A C D E)) returns #F (DEFINE (equalsimp? lis1 lis2) (COND ((NULL? lis1) (NULL? lis2)) ((NULL? lis2) #F) ((EQ? (CAR lis1) (CAR lis2)) (equalsimp?(CDR lis1)(CDR lis2))) (ELSE #F) ))© 2007 Addison-Wesley. All rights reserved. Copyright 1-43 Example Scheme Function: append • append takes two lists as parameters; returns the first parameter list with the elements of the second parameter list appended at the end e.g:(append ‘(A B) ‘(C D R))returns(A B C D R) (CONS ‘(A B) ‘(C D R))returns((A B) C D R) (append ‘((A B)C)‘(D(E F)))returns((A B) C D (E F)) (CONS‘((A B)C)‘(D(E F)))returns(((A B) C) D (E F)) Copyright © 2007 Addison-Wesley. All rights reserved. 1-44 A Scheme Function Example : guess • Function name: guess • Input: takes 2 parameters which are simple lists; • Output: returns a simple list that contains the common elements of its two parameter lists. • Example: (guess‘(E A B D) '(F C D A))returns (A D) (DEFINE (guess lis1 lis2) (COND ((or (NULL? lis1) (NULL? lis2)) '()) ((member (CAR lis1) lis2) (CONS(CAR lis1)(guess(CDR lis1) lis2))) (ELSE (guess(CDR lis1) lis2)) )) Copyright © 2007 Addison-Wesley. All rights reserved. 1-45 Comparing Functional and Imperative Languages • Imperative Languages: – Efficient execution – Complex semantics – Complex syntax • Functional Languages: – Simple semantics – Simple syntax – Inefficient execution Copyright © 2007 Addison-Wesley. All rights reserved. 1-46 Chapter 16 Logic Programming Languages ISBN 0-321-49362-1 Introduction • Logic programming languages, sometimes called declarative programming languages • Express programs in a form of symbolic logic • Use a logical inferencing process to produce results • Declarative rather than procedural: – Only specification of results are stated (not detailed procedures for producing them) • Prolog is the only wide used logic language Copyright © 2007 Addison-Wesley. All rights reserved. 1-2 The Origins of Prolog • Developed, by Comerauer and Roussel (University of Aix-Marseille), with help from Kowalski ( University of Edinburgh) • Based on formal logic • Non-procedural • frequently used language in Artificial Intelligence • Prolog programs consist of collections of statements Copyright © 2007 Addison-Wesley. All rights reserved. 1-3 Terms • All Prolog statements are constructed from terms. • Term: a constant, variable, or structure • Constant: an atom or an integer • Atom: symbolic value of Prolog • Atom consists of either: – a string of letters, digits, and underscores beginning with a lowercase letter Copyright © 2007 Addison-Wesley. All rights reserved. 1-4 Terms: Variables • Variable: any string of letters, digits, and underscores beginning with an uppercase letter • Variables are not bound to types • Instantiation: binding of a variable to a value Copyright © 2007 Addison-Wesley. All rights reserved. 1-5 Terms: Structures • Structure: represents atomic proposition functor(parameter list) – functor: any atom – parameter list: any list of atoms, variables and structures • Structures can be thought as objects, that are specifying the facts in Prolog • Structures are relations, since they state relationships among terms. • Structures are also predicate when its context specifies it to be a query. Copyright © 2007 Addison-Wesley. All rights reserved. 1-6 Fact Statements • Used for the hypotheses • Facts should always begin with a lowercase letter and end with a full stop lowercase sunny. john_is_cold. peter_footballer. john_Forgot_His_Raincoat. fred_lost_his_car_keys . Copyright © 2007 Addison-Wesley. All rights reserved. 1-7 Fact Statements continued • Pose a query ?- john_is_cold. yes ?- raining. no ?- john_Forgot_His_Raincoat. yes ?- john_lost_his_car_keys. no Copyright © 2007 Addison-Wesley. All rights reserved. 1-8 Simple Fact Exercises • Which of the following are syntactically correct facts? Hazlenuts. tomsRedCar. 2Ideas. prolog Copyright © 2007 Addison-Wesley. All rights reserved. No Yes No No 1-9 Simple Fact Exercises continued • Given the database below, study the queries below it. Again indicate whether you think the goal will succeed or not blue_box. red_box. green_circle. blue_circle. orange_triangle. ?????- green_circle. circle_green. red_triangle. red_box. orange_Triangle. Copyright © 2007 Addison-Wesley. All rights reserved. Yes No No Yes No 1-10 Facts with Arguments • General syntax relation(<argument1>,<argument2>,..,<argumentN> ). • E.g.: female(shelley). // shelley is a female male(bill). // bill is a male father(bill, jake). // “bill is the father of jake” or “jake is the father of bill” or “bill and jake have same father.“ • This reversibility is very useful, but causes some risks Copyright © 2007 Addison-Wesley. All rights reserved. 1-11 Facts with Arguments continued • An example database. It details who eats what in some world model. eats(fred,oranges). eats(fred,t_bone_steaks). eats(tony,apples). eats(john,apples). eats(john,grapefruit). • Queries ????- eats(fred,oranges). eats(john,apples). eats(mike,apples). eats(fred,apples). Copyright © 2007 Addison-Wesley. All rights reserved. yes yes no no 1-12 Facts with Arguments continued • An example database. age(john,32). age(agnes,41). age(george,72). age(ian,2). age(thomas,25). • Queries ?- age(ian,2). ?- agnes(41). ?- age(ian,two) Copyright © 2007 Addison-Wesley. All rights reserved. Yes No No 1-13 Variables and Unification • How do we say something like "What does Fred eat?“ Suppose we had the following fact in our database: eats(fred,mangoes). ?- eats(fred,what). No • A variable is required E.g.: X, VaRiable, My_Name • ?- eats(fred,What). What = mangoes yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-14 Variables and Unification continued • An example database loves(john,mary). loves(fred,hobbies). • Queries ?- loves(john,Who). Who=mary yes ?- loves(arnold,Who) no ?- loves(fred,Who). Who = hobbies yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-15 Variables and Unification Exercise eats(fred,tomatoes). eats(Whom,What). Whom = fred, What = tomatoes Yes eats(fred,Food). eats(Person,jim). Person = fred, Food = jim Yes cd(29,beatles,sgt_pepper). cd(A,B,help). No, sgt_pepper and help don’t unify Copyright © 2007 Addison-Wesley. All rights reserved. 1-16 Variables and Unification Exercise cont. f(X,a). f(a,X). X = a Yes likes(jane,X). likes(X,jim). No, X can not be bound to both jane and jim Copyright © 2007 Addison-Wesley. All rights reserved. 1-17 Variables and Unification Exercise cont. f(X,Y). f(P,P). X = P, Y = P Hence X = Y Yes f(foo,L). f(A1,A1). A1 = foo, A1 = L Hence L = foo Yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-18 Rule Statements • Conditional statement • Right side: antecedent (if part) – May be single term or conjunction • Left side: consequent (then part) – Must be single term • Conjunction: multiple terms separated by logical AND operations, which is comma Copyright © 2007 Addison-Wesley. All rights reserved. 1-19 Rule Statements continued • E.g.: “All men will die”. as the following Prolog rule: die(X) :- human(X). • The clause can be read: If X is a human, X will die. • “Socrates is human” human(socrates). ?- die(socrates). X = socrates yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-20 Rule Statements continued • we can represent the sentence 'Something is fun if it is a red car or a blue bike or it is an ice cream' as follows: fun(X) :- red(X), car(X). fun(X) :- blue(X), bike(X). fun(ice_cream). • Identical variable names in separate rules are totally independent Copyright © 2007 Addison-Wesley. All rights reserved. 1-21 Rule Statements Examples • Consider the following program: fun(X) :- red(X), car(X). fun(X) :- blue(X), bike(X). car(vw_beatle). car(ford_escort). bike(harley_davidson). red(vw_beatle). red(ford_escort). blue(harley_davidson). ?- fun(harley_davidson). yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-22 Rule Statements Examples continued • Consider the following program: fun(X) :- red(X), car(X). fun(X) :- blue(X), bike(X). car(vw_beatle). car(ford_escort). bike(harley_davidson). red(vw_beatle). red(ford_escort). blue(harley_davidson). ?- fun(What). What = vw_beatle yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-23 Rule Statements Exercise • Given the database below: likes(john,mary). likes(john,trains). likes(peter,fast_cars). likes(Person1,Person2):hobby(Person1,Hobby), hobby(Person2,Hobby). hobby(john,trainspotting). hobby(tim,sailing). hobby(helen,trainspotting). hobby(simon,sailing). Copyright © 2007 Addison-Wesley. All rights reserved. 1-24 Rule Statements Exercise • Queries ????- likes(john,trains). likes(helen,john). likes(tim,helen). likes(john,helen). Copyright © 2007 Addison-Wesley. All rights reserved. Yes Yes No Yes 1-25 Search –Introducing Backtracking • An example Database eats(fred,pears). eats(fred,t_bone_steak). eats(fred,apples). • "What are all the things that fred eats?“ ?- eats(fred,FoodItem). FoodItem = pears • Prolog allows us to ask again to get other possible solutions. FoodItem = t_bone_steak • If I ask another solution, FoodItem = apples • If we ask for further solutions, no • The mechanism for finding multiple solution is called backtracking. Copyright © 2007 Addison-Wesley. All rights reserved. 1-26 Backtracking in Rules • Consider the following program: hold_party(X):-birthday(X),happy(X). birthday(tom). birthday(fred). birthday(helen). happy(mary). happy(jane). happy(helen). • Query ?- hold_party(Who). Who = helen yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-27 Search Examples • Consider the following program: fun(X) :- red(X), car(X). fun(X) :- blue(X), bike(X). /* database of red items */ red(apple_1). red(block_1). red(car_27). /* database of cars */ car(desoto_48). car(edsel_57). Copyright © 2007 Addison-Wesley. All rights reserved. 1-28 Search Examples continued • Query ?- fun(What). fun(What) :- red(What),car(What). red(apple_1). red(block_1). red(car_27). first choice car(desoto_48). car(edsel_57). This will fail Copyright © 2007 Addison-Wesley. All rights reserved. 1-29 Search Examples continued • Query ?- fun(What). fun(What) :- red(What),car(What). red(apple_1). red(block_1). red(car_27). second choice car(desoto_48). car(edsel_57). This will fail also Copyright © 2007 Addison-Wesley. All rights reserved. 1-30 Search Examples continued • Query ?- fun(What). fun(What) :- red(What),car(What). red(apple_1). red(block_1). red(car_27). third choice car(desoto_48). car(edsel_57). This will fail also Copyright © 2007 Addison-Wesley. All rights reserved. 1-31 Search Examples continued • Query /* clause 1 */ fun(X) :- red(X), car(X). we've tried this clause but without luck /* clause 2 */ fun(X) :- blue(X), bike(X). so lets have a go with this clause now Copyright © 2007 Addison-Wesley. All rights reserved. 1-32 Search Examples continued fun(X) :- blue(X), bike(X). /* database of blue items */ blue(flower_3). blue(glass_9). blue(honda_81). /* database of bikes */ bike(iris_8). bike(my_bike). bike(honda_81). ?- fun(What) What = honda_81 yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-33 Recursion • wish to repeatedly perform some operation • A program calls itself typically until some final point is reached • First fact, that is for stopping condition followed by some rule(s) Copyright © 2007 Addison-Wesley. All rights reserved. 1-34 Recursion examples on_route(rome). on_route(Place):- move(Place,Method,NewPlace), on_route(NewPlace). move(home,taxi,halifax). move(halifax,train,gatwick). move(gatwick,plane,rome). ?- on_route(home). yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-35 Recursion examples continued parent(john,paul). /* john is paul's parent */ parent(paul,tom). /* paul is tom's parent */ parent(tom,mary). /* tom is mary's parent */ ancestor(X,Y):- parent(X,Y). ancestor(X,Y):- parent(X,Z),ancestor(Z,Y). ?- ancestor(john,tom). yes ?- ancestor(john, paul). yes ?- ancestor(tom,paul). no ?- ancestor(paul,mary). Copyright © 2007 Addison-Wesley. All rights reserved. yes 1-36 Picture of the Situation ancestor(X,Y):- parent(X,Y). ancestor(X,Y):- parent(X,Z),ancestor(Z,Y). parent X Y ancestor parent X ancestor Z ancestor Copyright © 2007 Addison-Wesley. All rights reserved. Y 1-37 Recursion exercise • Which of the following programs uses recursion. a(X):- b(X,Y), a(X). Yes go_home(no_12). go_home(X):- get_next_house(X,Y),home(Y). No foo(X):- bar(X). No lonely(X):- no_friends(X). no_friends(X):- totally_barmy(X). No has_flu(rebecca). has_flu(john). has_flu(X):- kisses(X,Y),has_flu(Y). kisses(janet,john). Yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-38 List Structures • Other basic data structure (besides atomic propositions we have already seen): list • List is a sequence of any number of elements • Elements can be atoms, atomic propositions, or other terms (including other lists) [apple, prune, grape, kumquat] [mia, robber(honeybunny), X, 2, mia] [] (empty list) [mia,[vincent,jules],[butch, friend(butch)]] Copyright © 2007 Addison-Wesley. All rights reserved. 1-39 Head and Tail • A non-empty list can be thought of as consisting of two parts – The head – The tail • The head is the first item in the list • The tail is everything else – The tail is the list that remains when we take the first element away – The tail of a list is always a list Copyright © 2007 Addison-Wesley. All rights reserved. 1-40 Head and Tail Example 1 • [mia, vincent, jules, yolanda] Head: mia Tail: [vincent, jules, yolanda] Copyright © 2007 Addison-Wesley. All rights reserved. 1-41 Head and Tail Example 2 • [[ ], dead(z), [2, [b,c]], [ ], Z, [2, [b,c]]] Head: [ ] Tail: [dead(z), [2, [b,c]], [ ], Z, [2, [b,c]]] Copyright © 2007 Addison-Wesley. All rights reserved. 1-42 Head and Tail Example 3 • [dead(z)] Head: dead(z)] Tail: [ ] Copyright © 2007 Addison-Wesley. All rights reserved. 1-43 Head and Tail of empty list • The empty list has neither a head nor a tail • For Prolog, [ ] is a special simple list without any internal structure Copyright © 2007 Addison-Wesley. All rights reserved. 1-44 The built-in operator | • Prolog has a special built-in operator | which can be used to decompose a list into its head and tail • The | operator is a key tool for writing Prolog list manipulation predicates ?- [Head|Tail] = [mia, vincent, jules, yolanda]. Head = mia Tail = [vincent,jules,yolanda] yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-45 The built-in operator | ?- [X|Y] = [mia, vincent, jules, yolanda]. X = mia Y = [vincent,jules,yolanda] yes ?- [X|Y] = []. no Copyright © 2007 Addison-Wesley. All rights reserved. 1-46 The built-in operator | ?- [X,Y|Tail] = [[], dead(z), [2, [b,c]], [], Z, [2, [b,c]]] . X = [] Y = dead(z) Tail = [[2, [b,c]], [], Z, [2, [b,c]]] yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-47 More List Examples • [a,b,c] unifies with [Head|Tail] resulting in Head=a and Tail=[b,c] • [a] unifies with [H|T] resulting in H=a and T=[] • [a,b,c] unifies with [a|T] resulting in T=[b,c] • [a,b,c] doesn't unify with [b|T] • [] doesn't unify with [H|T] • [] unifies with []. Two empty lists always match Copyright © 2007 Addison-Wesley. All rights reserved. 1-48 List Examples continued • Consider the following fact. p([H|T], H, T). • Let’s see what happens when we ask some simple queries. ?- p([a,b,c], X, Y). X=a, Y=[b,c] yes ?- p([a], X, Y). X=a, Y=[] yes ?- p([], X, Y). no Copyright © 2007 Addison-Wesley. All rights reserved. 1-49 List Examples continued • Here are some problems for which unification sometimes succeeds and sometimes fails. • [a,d,z,c] and [H|T] H = a and T = [d,z,c] Yes • [apple,pear,grape] and [A,pear|Rest] A = apple and Rest = [grape] Yes • [a|Rest] and [a,b,c] Rest = [b,c] Yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-50 List Examples continued • Here are some problems for which unification sometimes succeeds and sometimes fails. • [one] and [Two] Two = one yes • [a,b,X] and [a,b,c,d] no X can not represent the two atoms c, d Copyright © 2007 Addison-Wesley. All rights reserved. 1-51 List Searching • Used lists within facts and rules. • Inspected the first element and then the rest of list for searching • Done by recursion • Pulled the list apart [Head|Tail] Copyright © 2007 Addison-Wesley. All rights reserved. 1-52 List Searching examples • Consider the following problem. How can we find whether a given item is the member of the given list (eg.: apples)? [pears, tomatoes, apples, grapes] of(Item,[Item|Rest]). of(Item,[DisregardHead|Tail]):of(Item,Tail). • Query ?- of(apples, [pears, tomatoes, apples, grapes]). yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-53 List Searching exercise • Given the following list of cities and features: [istanbul, antalya, trabzon, vienna, sarajevo] • Write a program called member, that would be able to see if something was a member of a list. The program would inform that ilidza was not on list by failing, yet confirm all the above were on the list by succeeding (answering yes). Copyright © 2007 Addison-Wesley. All rights reserved. 1-54 List Searching exercise member(X,[X|T]). member(X,[H|T]):- member(X,T). ?- member(istanbul,[istanbul,antalya, trabzon,vienna,sarajevo]) yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-55 List Searching exercise member(X,[X|T]). member(X,[H|T]):- member(X,T). ?- member(sarajevo,[istanbul,antalya, trabzon,vienna,sarajevo]) yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-56 List Searching exercise member(X,[X|T]). member(X,[H|T]):- member(X,T). ?- member(ilidza,[istanbul,antalya, trabzon,vienna,sarajevo]) no Copyright © 2007 Addison-Wesley. All rights reserved. 1-57 List Construction • To build a new list E.g.: List1 = [lisp,c,pascal,basic] List2 = [prolog|List1] List2 = [prolog,lisp,c,pascal,basic] • to build a new list from two existing lists – Illustrated by defining the predicate append – Append takes 3 arguments. At least two arguments are list. E.g.: ?- append([a,b,c],[one,two,three],Result). Result = [a,b,c,one,two,three] Copyright © 2007 Addison-Wesley. All rights reserved. 1-58 Append Examples ?- append([a,b,c,d],[3,4,5],[a,b,c,d,3,4,5]). yes ?- append([a,b,c],[3,4,5],[a,b,c,d,3,4,5]). no ?- append([a,b,c,d],[1,2,3,4,5], X). X=[a,b,c,d,1,2,3,4,5] yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-59 List Construction Example • Taking the list [1,12,3,14,5,8], lets construct a new list out of the old that contains only numbers greater than 6. sift([],[]). sift([X|T],[X|Result]):- X > 6, sift(T,Result). sift([ThrowAway|Tail],Result):sift(Tail,Result). Result = [12,14,8] Copyright © 2007 Addison-Wesley. All rights reserved. 1-60 List Construction Exercise • Write a program to delete all reference of a particular item from a list. It should have three arguments. The list you wish to use, the item to delete, and the resulting list. Here are some example of it behaviour ?- delete_all([a,b,a,c,a,d],a,Result). Result = [b,c,d] ?- delete_all([a,b,a,c,a,d],b,Result). Result = [a,a,c,a,d] ?- delete_all([a,b,a,c,a,d],prolog,Result). Result = [a,b,a,c,a,d] Copyright © 2007 Addison-Wesley. All rights reserved. 1-61 List Construction Exercise delete_all(Item,[],[]). delete_all(Item,[ThrowAway|Tail],Result):same(Item,[Item|Tail]), delete_all(Item,Tail,Result). delete_all(Item,[ThrowAway|Tail],Result):append(ThrowAway,List,Result), delete_all(Item,Tail,Result). Copyright © 2007 Addison-Wesley. All rights reserved. 1-62 Simple Arithmetic • Prolog supports integer variables and integer arithmetic • is operator: takes an arithmetic expression as right operand and variable as left operand A is B / 17 + C • Not the same as an assignment statement! Copyright © 2007 Addison-Wesley. All rights reserved. 1-63 Simple Arithmetic continued • Arithmetic examples • Prolog Notation 8 is 6+2. 12 is 6*2. 4 is 6-2. -2 is 6-8. 3 is 6/2. 3 is 7/2. 1 is mod(7,2). //1 is the remainder when 7 is divided by 2 Copyright © 2007 Addison-Wesley. All rights reserved. 1-64 Simple Arithmetic continued • Posing the following queries yields the following responses: ?- 8 is 6+2. yes ?- 12 is 6*2. yes ?- -2 is 6-8. yes ?- 3 is 6/2. yes ?- 1 is mod(7,2). yes Copyright © 2007 Addison-Wesley. All rights reserved. 1-65 Simple Arithmetic continued • we can work out the answers to arithmetic questions by using variables. ?- X is 6+2. X = 8 ?- X is 6*2. X = 12 ?- R is mod(7,2). R = 1 ?- X is 3+2*4. X = 11 Copyright © 2007 Addison-Wesley. All rights reserved. 1-66 Simple Arithmetic Example speed(ford,100). speed(chevy,105). speed(dodge,95). speed(volvo,80). time(ford,20). time(chevy,21). time(dodge,24). time(volvo,24). distance(X,Y) :- speed(X,Speed), time(X,Time), Y is Speed * Time. Copyright © 2007 Addison-Wesley. All rights reserved. 1-67 Simple Arithmetic Example • Query ?- distance(chevy,Chevy_Distance) Chevy_Distance = 2205 Copyright © 2007 Addison-Wesley. All rights reserved. 1-68 Applications of Logic Programming • Relational database management systems • Expert systems • Natural language processing Copyright © 2007 Addison-Wesley. All rights reserved. 1-69 Summary • Symbolic logic provides basis for logic programming • Logic programs should be nonprocedural • Prolog statements are facts, rules, or goals • Resolution is the primary activity of a Prolog interpreter • Although there are a number of drawbacks with the current state of logic programming it has been used in a number of areas Copyright © 2007 Addison-Wesley. All rights reserved. 1-70