PL Quiz (post exam#1)

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

References to Records

1. COBOL: (inmost-out) -field_name OF record_name_n OF .. OF record_name_1 2. Others (dot notation): (outmost-in) -record_name_1.record_name_2...record_name_n.field_name Fully qualified references must include all record names Elliptical references allow leaving out record names as long as teh reference is unambiguous

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 If we use these for our loop counter variables, then we can never access an array beyond its bounds!

Evaluation of Enumerated Type

Aid to readability, e.g., no need to code a color as a number • 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

Character String Type Evaluation

Aid to writability • As a primitive type with static length, they are inexpensive to provide--why not have them? - Many languages provide strings via a standard library package, which is nearly as convenient • Dynamic length is nice, but is it worth the expense? - Current machines (fast CPUs with lots of memory) make this concern less of a factor

Enumeration Types

All possible values, which are named constants, are provided in the definition • C# example enum day {Mon, Tue, Wed, Thu, Fri, Sat, Sun}; • Design issues (all relate to type checking): - Is an enumeration constant allowed to appear in more than one type definition, and if so, how is the type of an occurrence of that constant checked? enum planet {Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune}; - Are enumeration values coerced to integer? - Any other type coerced to an enumeration type?

Primitive Data Types

Almost all programming languages provide a set of primitive data types -Are those data types 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

Primitive Data Types: Integer

Almost always an exact reflection of the hardware so the mapping is trivial -May be as many as eight different integer types in a language -Byte, short, int, long

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

Subrange Types

An ordered contiguous subsequence of an ordinal type - Example: 12..18 is a subrange of integer type • Ada's design: type Day is (Mon, Tue, Wed, Thu, Fri, Sat, Sun); subtype Weekday is Day range Mon..Fri; subtype Index is Integer range 1..100; Day1: Day; Day2: Weekday; Day2 := Day1; //compiler must generate range checking code

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

Dictionaries in Python

Associative arrays in Python are called dictionaries -very popular aspect of python -easy to initialize and add/delete pairs

Array indexing

Indexing (or subscripting) is a mapping from ndices to elements - array_name (index_value_list) → an element Index Syntax - FORTRAN, PL/I, Ada use parentheses • Ada explicitly chose parentheses to show uniformity between array references and function calls because both are mappings - Most other languages use brackets • Brackets allow the compiler to disambiguate the construct earlier in the compilation process - This is also a readability issue

Primitive Data Types: Floating Point

Model real numbers, but only as approximations -Languages for scientific use support at least two floating-point types (eg. float and double) sometimes more -Usually exactly like the hardware, but not always

Implementation fo Record Type

Record Descriptor: offset address relative to teh beginning of the records is associated with each field

Definitions of Records

Record structures are indicated in an orthogonal way -check ppt 20 for examples

Record/Struct Types

Record: aggregate of possibly heterogeneous data elements in which the individual elements are identified by names -allos us to operate on a collection of data that is not homogeneous (as in arrays) -first introduced in Cobol, and supported by most popular language -design issues: what is the syntactic form of the references to the field? are elliptical references allowed?

Field references

Referencing record elements, or fields, is usually by name rather than by index

Prolog Scope

Scope of a variable is the clause in which it appears -Variables whose first appearance is on the left hand side of the clause have implicit universal quantifiers (for-all) -Variables whose first appearance is in the body of the clause have implicit existential quantifiers (there-exists)

Primitive Data Types: Boolean

Simplest of all -Range of values: two elements, one for "true" and one for "false" -Could be implemented as a bit, but often as a byte -Advantage: readability in logic expressions (as opposed to interpreting numeric expressions)

Primitive Data Types: Complex

Some languages support a complex type eg. Fortran and Python -each value consists of two floats, the real part and the imaginary part -Literal form: (7 + 3j), where 7 is the real part and 3 is the imaginary part - Why 'j' and not 'i', which mathematicians use?? - Maybe because EE's use 'j' rather than 'i'

Subscript Binding and Array Categories

Static Fixed stack-dyamic Stack-dyanmic Fixed heap-dynamic Heap Dynamic

Character String length Opeartions

Static Length: COBOL - The text author classifies Java's String class here, but I disagree • Limited Dynamic Length: C and C++ - In these languages, a special character is used to indicate the end of a string's characters, rather than maintaining the length - Read article from CACM, 9/2011 (posted with lecture notes) • Dynamic (no maximum): SNOBOL4, Perl, JavaScript • Ada supports all three string length options

Character String Implementation

Static length: compile-time descriptor • Limited dynamic length: may need a run-time descriptor for length - but not in C and C++ which use a null terminator • Dynamic length: need run-time descriptor - allocation/de-allocation is the biggest implementation problem

Primitive Data Type: Character

Stored as numeric codings -Most commonly used coding ASCII -An alternative, 16-bit coding: Unicode (includes characters from most natural languages, originally used in Java, C#, Perl, Python, Javascript also support Unicode) -There is also now a 32-bit Unicode standard

Union

Type whose variables are allowed to store different type values at different time during execution -design issues: should type checking be required? should unions be embedded in records?

Associative Array

Unordered collection of data elements that are indexed by an equal number of values called keys -creates a key -> element mapping 9like a regular array) -user defined keys must be stored -elements are essentially key and value pairs -ex. hashes in Perl or dictionaries in Python -often implemented as hash tables (allso efficient lookup for large arrays) -Design Issues: what is the form of references to elements? and is the size static or dynamic?

Prolog Interpreter

To run a program one ask the interpreter a question -This is done by stating a theorem (asserting a predicate) which the interpreter tries to prove -if it can prove the theorem it says yes -if it can't it says no -if your predicate contained variables, the interpreter prints the values it had to give the variables to make the predicate true -works by BACKWARD CHAINING, which means it begins with the thing it is trying to prove and works backwards looking for things that would imply it, until it gets to facts

Subscript Binding and Array Categories: Fixed heap-dynamic

similar to fixed stack-dynamic: storage binding is dynamic but fixed after allocation (i.e., binding is done when requested and storage is allocated from heap, not stack)

Subscript Binding and Array Categories: Stack-dynamic

subscript ranges are dynamically bound and the storage allocation is dynamic (done at run-time); ranges are fixed once set - Advantage: flexibility (the size of an array need not be known until the array is to be used)

Subscript Binding and Array Categories: Static

subscript ranges are statically bound and storage allocation is static (before run-time) - Advantage: efficiency (no dynamic allocation)

Subscript Binding and Array Categories: Fixed Stack-dynamic

subscript ranges are statically bound, but the allocation is done at declaration elaboration time - Advantage: space efficiency

Array Index (Subscript) Types

• FORTRAN, C: integer only • Ada: integer or enumeration (includes Boolean and char) • Java: integer types only • Index range checking - Range checking can improve reliability of programs, but adds a runtime cost - C, C++, Perl, and Fortran do not specify range checking - Java, ML, C# specify range checking - In Ada, the default is to require range checking, but it can be turned off

Array Design Issues

• What types are legal for subscripts? • Are subscripting expressions in element references range checked? • When are subscript ranges bound? • When does allocation take place? • What is the maximum number of subscripts? - Are multidimensional arrays ragged or rectangular? • Can array objects be initialized? • Are any kind of slices supported?

Tuple Types

Used in Python, ML, F# to allow functions to return multiple values -Python: closely related to its Python lists, but immutable; create with a tuple literal (ex. myTuple = (3, 5.8, 'apple)); referenced with subscripts (begin at 0); catenation and + and deleted with del -ML: (ex. val myTuple = (3, 5.8, 'apple');); access as follows: #1 (myTuple is the first element; a new tuple type can be defined: type intReal = int * real; -F#: (ex. let tup = (3, 5, 7); let a, b, c = tup assigns a tuple to a tuple pattern (a, b, c)

Character String Types and Operations

Values are sequences of characters Design issues: - Is it a primitive type or just a special kind of array? - Should the length of strings be static or dynamic? Typical Operations -Assignment and copying • What if strings are of different lengths? - Comparison (=, >, etc.) - Concatenation - Substring reference - Pattern matching

Data type

defines a collection of data objects and a set of predefined operations on those objects

Prolog Rules

-Rules are theorems that allow the interpreter to infer things -Usually contain variables -Ex. employed(X) :- employs(Y, X) can be read as for all X, X is employed if there exists a Y such tat Y employs X -note the direction of teh implication b/c it DOES NOT SAY that X is employed ONLY IF there is a Y that employs x

Prolog Interpreter with the Stack

-When it attempts resolution, Prolog interpreter pushes the current goal onto a stack, makes the first term in the body the current goal, and goes back to beginning of the database and starts looking again -If it gets through the first term/goal of a body successfully, the interpreter continues with the next one -If it gets all the way through the body the goal is satisfied and it backs up a level and proceeds

Logic Programming Concepts #2

-A structure can play teh role of a data structure or a predicate -Constant is eitehr an atom or a number -atom is either what looks like an identifier beginnig with a lower-case letter or a quoted character string -a number looks like an integer or real from some more ordinary language -a variable looks like an identifier beginning with an upper-case letter -there are no declarations -all types are discovered implicitly -meaning of teh statement is that teh conjunction of teh terms in teh body implies the head -clause with an empty body is called a FACT -clause with an empty head is a QUERY, or top level GOAL -clause with both sides is a RULE -Facts are axioms - things teh interpreter assumes to be true in Prolog

Operations on Records

-Assignment is very common if the types are identical -Ada allows record comparsion -Ada records can be initialized with aggregate literals -COBOL provides MOVE CORRESPONDING (copies all fields of the source record to teh corresponding fields in the targe record if they have the same name & useful in many data-processing applications)

Logic Programming

-Based on Predicate calculus, whereas functional programming is based on lambda calculus -Predicates are buliding blocks (ex. enrolled(you, cs3270)) that we attaching meaning to but within the logical system they are simply structural building blocks

Prolog

-Can be thought of declaratively or imperatively -Allows you to state a bunch of axioms and rules; tehn you pose a query (goal) and the system tries to find a series of inference steps (and assignments of values to variables) that allow it to prove your query starting from the axioms -ex. mother(mary, fred) - can think of that as a predicate asserting that mary is mother of fred OR a data structure (tree_ in which teh functor (atom) mother is the root, mary is the left child, and fred is the right child

Discriminated vs. Free Unions

-Fortran, C, and C++ provide union constructs in which there is no language support for type checking; the union in these languages are called FREE UNION (allows you to avoid type checking and create unsafe code) -Type Checking of unions require that each union include a type indicator called a DISCRIMINANT; supported by Ada

Evaluation of Unions

-Free unions are unsafe b/c do not allow type checking, which is why Fortran, C, and C++ are not strongly typed -Java and C# do not support unions, which is reflective of growing concerns for safety in programming language -Ada's discriminated unions are safe, since you must assign an entire record (cannot just change one field)

Backtracking

-If it fails to satisfy the terms in the body of the rule, interpreter undoes the unifiaction of the LHS (includes uninstantiating any variables that were given values as a result of unification) and keeps looking through the database for something else with which to unify (BACKTRACKING) -If interpreter gets to the end of database without succeeding, it backs out a level and continues from there -Visualize it as a tree in which the top-level goal is the root and the leaves are facts (interpreter does an OR across rules and facts if any one of them succeeds then teh goal succeds, and an AND across terms in the body of teh rule if all of them must succeed in order for parent to succed

List Types

-ML: lists are written in brackets and the elements are separated by commas; list elemetns must be of the same type which allows ML to be statically type; lisp CONS function is a binary operator in ML, :: ;lisp car and cdr are hd and tl -F#: like those of ML, except elements are separated by semicolons and hd and tl are methods of the List class -Python Lists: list data type also serves as Python's array; unlike Scheme, ML, and F#, Python's lists are mutable; elements can be any type; create a list with an assignment; list elements are referenced with subscripting with indices beginning at zero, lists elements can be deleted with del

Associative Arrays in perl

-Names begin with %; literals are delimited by parentheses (ex. %hi_temps = ("Mon" => 77, "Tue" => 70); -Subscripting is done using braces and keys (since a scalar value is returned, subscripting uses scalar variable name starting with $) (ex. $hi_temps{"Wed} = 83;) -Elements can be removed with delete (ex. delete $hi_temps{"Tue"}

Logic Programming Concepts

-Operators: conjunction, disjunction, negation, implication -Universal and existential quantifiers -Statements: sometimes true, sometimes false, often unknown; axioms- assumed true; theorems- provably true; hypotheses- things we'd like to prove true -Most statements can be written many ways -Great for people but a nuissance for computers -Logic programming systems put certain restrictions on teh format of teh statements you can prove theorems mechanically -insist that all statements be in the form of HORN CLAUSES consisting of a HEAD and a BODY -a term can be a constant, variable or a STRUCTURE consisting of a FUNCTOR and a parenthesized list of arguments

Prolog Interpreter Timeline

-Predicate you ask for is the interpreter's original GOAL -In an attempt to SATISFY the goal, it looks for facts or rules with which the goal can be UNIFIED (unification is a process by which compatible statements are merged) -any variables that do not yet have values which correspond to constants or to variables with values in the other clause get INSTANTIATED with that value -anyplace where uninstantiated variables correspond, those variables are identified with each other, but remain without values -starts at the beginning of your database and looks for something which to unify the current goal -if it finds a fact it succeeds -if it finds a rule it attempts to satisfy the terms in the body of the rule (the RHS) depth first -process motivated by the RESOLUTION PRINCIPLE

List

-Primary structure of LISP and Scheme -Lists in LISP and Scheme are delimited by parentheses and use no commas -data and code have teh same form -interpreter needs to know which is a list is, so if it is data, we quote it with an apostrophe

Prolog database, facts, rules, variables, query

-Prolog database is made up of facts and rules -Facts are defined using predicates that do not use variables -Rules are defined using predicates that do use variables -Variables are identifiers that start with an uppercase letter -When you pose a query it will return first answer it finds

Evaluation and Comparison to Arrays

-Records are used when collection of data values is finite and heterogeneous -Design is straightforward and their use is safe -Access to array elements is much slower than access to record fields, b/c subscripts are dynamic (field names are static) -Dynamic subscripts could be used with record field access, but it would disallow type checking and it would be much slower

Character String Type in Certain Languages

C and C++ (cstrings) - Not primitive - Use null-terminated char arrays and a library of functions that provide operations • Many operations are unsafe (buffer overflow issues) • SNOBOL4 (a string manipulation language) - Primitive - Many operations, including elaborate pattern matching • Fortran 95 and Python - Primitive type with assignment and several operations • Java - Primitive via the String class - Values are constant strings (no mutation) • Perl, JavaScript, Ruby, and PHP - Provide built-in pattern matching, using regular expressions

Definitions of Records in COBOl

COBOL uses level numbers to show nested records; others use recursive definitions -check ppt 20 for examples

Descriptor

Collection of the attributes of a variable -can be static or dynamic -static descriptors are maintained by the compiler -dynamic descriptors must be managed at runtime

Tuple

Data Type that is similar to a record, except that the elements are not named

Compile- and Run-Time Descriptors

Descriptors contain type name, length, and address pointer Compile-time descriptor for static strings Run-time descriptor for limited dynamic strings Reading a descriptor: top row identifies the descriptor type; the other rows are data of the descriptor (attributes)

Implementation of User-Defined Ordinal Types

Enumeration types are usually implemented as integers Subrange types are implemented like the parent types with code inserted (by the compiler) to restrict assignments to subrange variables - Ada is the only contemporary language to support subrange types

Primitive Data Types: Decimal

For business applications (representing money) - essential to COBOL, #C offers a decimal data type -Store a fixed number of decimal digits, in coded form -Advantage: accuracy -Disadvantage: limited range, wastes memory, not all CPUS have direct hardware support

Subscript Binding and Array Categories: heap-dynamic

binding of subscript ranges and storage allocation is dynamic and can change any number of times - Advantage: flexibility (arrays can grow or shrink during program execution)


Ensembles d'études connexes

Derm - Peds Primary Care 1 - Exam 2

View Set

Nursing Care of Children Post-study quiz

View Set

Chapter 9: Health Promotion of the Infant and Family

View Set

Intro to Research - How to read a journal article

View Set

PowerPoint Modules 1-3 Review Questions

View Set