Summary

This document provides a detailed explanation of data types in programming. It covers primitive data types like integers, floating-point numbers, booleans, and characters, and their implementation in various languages. It also explores string types, including dynamic and static options. The document mentions user-defined types such as enumeration types, and how they are implemented in different contexts.

Full Transcript

Concept Lec 3 Introduction - A data type defines a collection of data objects and a set of predefined operations on those objects. - A descriptor is the collection of the attributes of a variable. - An object represents an instance of a user-defined (abstract data) type. Primitive Data...

Concept Lec 3 Introduction - A data type defines a collection of data objects and a set of predefined operations on those objects. - A descriptor is the collection of the attributes of a variable. - An object represents an instance of a user-defined (abstract data) type. 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 hardware. - Others require only a little non-hardware support for their implementation. - Primitive Data Types (7 types) Integer: Floating Point: - Almost always an exact reflection of the hardware - Model real numbers, but only as approximations. so the mapping is trivial. - Languages for scientific use support at least two - There may be as many as eight different integer floating-point types (EX: float and double). types in a language. - Usually exactly like the hardware, but not always. - Java’s signed integer sizes: byte, short, int, long. - IEEE Floating-Point Standard 754 Complex: Decimal: - Some languages support a complex type, EX: C99, - For business applications (money) Fortran, and Python. Essential to COBOL. - Each value consists of two floats, the real part, and C# offers a decimal data type. the imaginary part. - Store a fixed number of decimal digits, in coded - Literal form (in Python): form (BCD) - Adv: accuracy - Disadvantages: limited range, wastes memory. Boolean: Character: - Range of values: two elements, one for “true” and - Stored as numeric coding. one for “false”. - used coding: ASCII. - Could be implemented as bits, but often as bytes. - 16-bit coding: Unicode (UCS-2) - Adv: readability. Originally used in Java. C# and JavaScript also support Unicode. - 32-bit Unicode (UCS-4) Supported by Fortran, starting with 2003 Character String Types: - Values are sequences of characters. - Aid to writability. - Operations: (5 operations) (Assignment and copying – Comparison (=, >, etc.) – Catenation – Substring reference – Pattern matching) - EX: C and C++  Not primitive.  Use char arrays and a library of functions that provide operations. SNOBOL4 (a string manipulation language)  Primitive  Many operations, including elaborate pattern matching. Fortran and Python  Primitive type with assignment and several operations. Java  Primitive via the String class Perl, JavaScript, Ruby, and PHP  Provide built-in pattern matching, using regular expressions. - String Length Options: (3 type) Static:  COBOL, Java’s String class.  compile-time descriptor. Limited Dynamic Length  a special character in C and C++ is used to indicate the end of a string’s characters, rather than maintaining the length.  may need a run-time descriptor for length (but not in C and C++) Dynamic (no maximum)  SNOBOL4, Perl, JavaScript  need run-time descriptor; allocation/deallocation is the biggest implementation problem. Ada supports all three string length options. User-Defined Ordinal Types (2 type) - An ordinal type is one in which the range of possible values can be easily associated with the set of positive integers. - Ex: in Java ➔ (integer – char – Boolean). - Enumeration Types: o All possible values, which are named constants, are provided in the definition. o Ex: in C# ➔ o Aid to readability, Ex: no need to code a color as a number. o Aid to reliability, Ex: 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. - Subrange Types o An ordered contiguous subsequence of an ordinal type. o Ex: in Ada ➔ o Aid to readability – Make it clear to the readers that variables of subrange can store only certain range of values. o Reliability – Assigning a value to a subrange variable that is outside the specified range is detected as an error. - Enumeration types are implemented as integers. - Subrange types are implemented like the parent types with code inserted (by the compiler) to restrict assignments to subrange variables. Array Types - An array is a homogeneous aggregate of data elements in which an individual element is identified by its position in the aggregate, relative to the first element. - Array Indexing o Indexing or subscripting is a mapping from indices to elements. EX: o Index Syntax ✓ Fortran and Ada use parentheses ( ) ✓ Most other languages use brackets [ ] o Index (Subscript) Types ✓ FORTRAN, C, Java: integer only ✓ Ada: integer or enumeration (includes Boolean and char) o Index range checking ✓ 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. Subscript Binding and Array Categories (4 type) Fixed Static Stack-dynamic Heap-dynamic stack-dynamic Heap-dynamic Subscript Subscript ranges like fixed stack- Subscript ranges Binding of Subscript ranges are statically dynamic. are dynamically subscript ranges is ranges are statically bound. bound. dynamic. bound. Storage Storage allocation Storage binding is The storage Storage allocation allocation is is done. dynamic but fixed allocation is is dynamic. static. (At declaration after allocation. dynamic. (Before run- time). (Done at run-time) can change any Storage time) Binding is done when number of times. requested and storage is allocated from heap, not stack. efficiency (no space efficiency. flexibility (the size flexibility (arrays dynamic of an array need can grow or shrink allocation). not be known until during program Adv the array is to be execution). used). C and C++ C and C++ arrays C# includes a second Perl, JavaScript, arrays that without static array class ArrayList Python, and Ruby includes static modifier are fixed that provides fixed support heap- modifier are stack dynamic. heap dynamic. dynamic arrays. EX static. C and C++ arrays provide fixed heap- dynamic arrays. o C and C++ arrays ✓ That includes static modifier are static. ✓ Without static modifier are fixed stack dynamic. ✓ provide fixed heap-dynamic arrays. - Array Initialization o Some languages allow initialization at the time of storage allocation. o EX: ✓ C, C++, Java, C# ➔ ✓ Character strings in C and C++ ➔ ✓ Arrays of strings in C and C++ ➔ ✓ Java initialization of String objects ➔ ✓ Ada ➔ ✓ Python ➔ List comprehensions - Heterogeneous Arrays o A heterogeneous array is one in which the elements need not be of the same type. o Supported by Perl, Python, JavaScript, and Ruby. - Arrays Operations o APL ➔ provides the most powerful array processing operations for vectors and matrixes as well as unary operators (EX: to reverse column elements) o Ada ➔ allows array assignment but also catenation. o Python’s ➔ array assignments, but they are only reference changes. ➔ supports array catenation and element membership operations. o Ruby ➔ also provides array catenation. o Fortran ➔ provides elemental operations because they are between pairs of array elements. ➔ ) EX: + operator between two array). - Rectangular and Jagged Arrays o 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. ✓ EX: Fortran, Ada, and C# o Possible when multi-dimensioned arrays appear as arrays of arrays. o A jagged matrix: ✓ has rows with varying number of elements. ✓ EX: C#, C, C++, and Java. - Multi-dimensioned o Two common ways: ✓ Row major order (by rows) – used in most languages. ✓ Column major order (by columns) – used in Fortran. o A compile-time descriptor for a multidimensional array. ✓ location (a[i, j]) = address of a[0, 0] + (((i * n) + j) *element_size) o General format: ✓ Location (a[i,j]) = address of a [row_lb,col_lb] + (((i - row_lb) * n) + (j - col_lb)) * element_size - Slices o A slice is some substructure of an array; nothing more than a referencing mechanism. o Slices are only useful in languages that have array operations. o EX: ✓ Python ➔ ✓ Ruby supports slices with the slice method ➔ Syntax: Slice (start_index, number_elements) - Implementation of Arrays o Access function maps subscript expressions to an address in the array. o Access function for single-dimensioned arrays. ✓ address(list[k]) = address(list) + k * element_size o In general ✓ address(list[k]) = address (list[lower_bound]) + ((k-lower_bound) * element_size) Associative Arrays - An associative array is an unordered collection of data elements that are indexed by an equal number of values called keys. - User-defined keys must be stored. - Built-in type in Perl, Python, Ruby, and Lua o In Lua, they are supported by tables. o In Perl ✓ Names begin with %, literals are delimited by parentheses. %hi_temps = ("Mon" => 77, "Tue" => 79, "Wed" => 65, …); ✓ Subscripting is done using braces and keys. ➔ $hi_temps{"Wed"} = 83; ✓ Elements can be removed with deleted. ➔ delete $hi_temps{"Tue"}; Record - Types o A record is a possibly heterogeneous aggregate of data elements in which the individual elements are identified by names. o Definition of Records in COBOL: COBOL uses level numbers to show nested records; others use recursive definition. o Definition of Records in Ada: Record structures are indicated in an orthogonal way. - References o In COBOL: ✓ field_name OF record_name_1 OF... OF record_name_n o Others (dot notation): ✓ record_name_1.record_name_2.... record_name_n.field_name o Fully qualified references must include all recorded names. o Elliptical references allow leaving out record names if the reference is unambiguous. EX: in COBOL FIRST, FIRST OF EMP-NAME, and FIRST of EMP-REC are elliptical references to the employee’s first name. - Operations o Assignment is very common if the types are identical. o Ada: ✓ Ada allows record comparison. ✓ Ada records can be initialized with aggregate literals. o COBOL: ✓ COBOL provides MOVE CORRESPONDING. ✓ Copies a field of the source record to the corresponding field in the target record. - Evaluation and Comparison to Arrays o Records are used when collection of data values is heterogeneous. o Access to array elements is much slower than access to record fields because subscripts are dynamic (field names are static). o Dynamic subscripts could be used with record field access, but it would disallow type checking and it would be much slower. - Implementation of Record Type o The offset address relative to the beginning of the record is associated with each field. Tuple Types - A tuple is a data type that is like a record, except that the elements are not named. - Used in Python, ML, and F# to allow functions to return multiple values. o Python ✓ Closely related to its lists, but immutable ✓ Create with a tuple literal ✓ myTuple = (3, 5.8, ′apple′) ✓ Referenced with subscripts (begin at 1) ✓ Catenation with + and deleted with del o ML ✓ 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; o F# ✓ let tup = (3, 5, 7) ✓ let a, b, c = tup This assigns a tuple to a tuple pattern (a, b, c), where a=3, b= 5 and c=7 List Types - Lists in LISP and Scheme are delimited by parentheses and use no commas. EX: (A B C D) and (A (B C) D) - Data and code have the same form o As data, (A B C) is literally what it is o As code, (A B C) is the function A applied to the parameters B and C - The interpreter needs to know which a list is, so if it is data, we quote it with an apostrophe. EX: ′ (A B C) is data - List Operations: o In Scheme ✓ CAR returns the first element of its list parameter. EX: (CAR ′ (A B C)) returns A ✓ CDR returns the remainder of its list parameter after the first element has been removed EX: (CDR ′ (A B C)) returns (B C) ✓ CONS puts its first parameter into its second parameter, a list, to make a new list EX: (CONS ′A (B C)) returns (A B C) ✓ LIST returns a new list of its parameters EX: (LIST ′A ′B ′ (C D)) returns (A B (C D)) o In ML ✓ Lists are written in brackets and the elements are separated by commas. ✓ List elements must be of the same type. ✓ The Scheme CONS function is a binary operator in ML ➔ :: EX: 3 :: [5, 7, 9] evaluates to [3, 5, 7, 9] ✓ The Scheme CAR and CDR functions are named hd and tl, respectively. o In F# ✓ Like those of ML, except elements are separated by semicolons and hd and tl are methods of the List class. ✓ List Comprehensions. EX: let myArray = [|for i in 1.. 5 -> [i * i) |] o In Python ✓ The list data type also serves as Python’s arrays. ✓ Unlike Scheme, Common LISP, ML, and F#. ✓ Python’s lists are mutable. ✓ Elements can be of any type. ✓ Create a list with an assignment. EX: myList = [3, 5.8, "grape"] ✓ List elements are referenced with subscripting, with indices beginning at zero EX: x = myList Sets x to 5.8 ✓ List elements can be deleted with del. EX: del myList ✓ List Comprehensions – derived from set notation EX: [x * x for x in range (6) if x % 3 == 0] range (6) creates [0, 1, 2, 3, 4, 5, 6] Constructed list: [0, 9, 36] o In Haskell ✓ List Comprehensions – The original. EX: [n * n | n 2 Operations o 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. ❖ Dereferencing can be explicit or implicit. ❖ C++ uses an explicit operation via *. ❖ EX: j = *ptr sets j to the value located at ptr. - Problems with Pointers o Dangling pointers (dangerous) – A pointer points to a heap-dynamic variable that has been deallocated. o Lost heap-dynamic variable – An allocated heap-dynamic variable that is no longer accessible to the user program (often called garbage) EX: ✓ Pointer p1 is set to point to a newly created heapdynamic variable ✓ Pointer p1 is later set to point to another newly created heap-dynamic variable ✓ The process of losing heap-dynamic variables is called memory leakage - Pointers in o Ada ✓ Some dangling pointers are disallowed because dynamic objects can be automatically deallocated at the end of pointer's type scope. ✓ The lost heap-dynamic variable problem is not eliminated by Ada (possible with UNCHECKED_DEALLOCATION) o 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. ✓ Used for dynamic storage management and addressing. ✓ Pointer arithmetic is possible. ✓ Explicit dereferencing and address-of operators. ✓ Domain type need not be fixed (void *) void * can point to any type and can be type checked (cannot be de-referenced). - Dangling Pointer Problem o Tombstone: extra heap cell that is a pointer to the heap-dynamic variable. ✓ The actual pointer variable points only at tombstones. ✓ When heap-dynamic variable de-allocated, tombstone remains but set to nil. ✓ Costly in time and space. o Locks-and-keys: Pointer values are represented as (key, address) pairs. ✓ Heap-dynamic variables are represented as variable plus cell for integer lock value. ✓ When heap-dynamic variable is allocated, lock value is created and placed in lock cell and key cell of pointer. - Reference Types o C++ includes a special kind of pointer type called a reference type that is used primarily for formal parameters. Adv: of both pass-by-reference and pass-by-value. o Java extends C++’s reference variables and allows them to replace pointers entirely. o References are references to objects, rather than being addresses. o C# includes both the references of Java and the pointers of C++ - Evaluation of Pointers o Dangling pointers and dangling objects are problems as is heap management. o Pointers are like goto's--they widen the range of cells that can be accessed by a variable. o Pointers or references are necessary for dynamic data structures--so we can't design a language without them. - Representations of Pointers o Large computers use single values. o Intel microprocessors use segment and offset. Type Checking - Generalize the concept of operands and operators to include subprograms and assignments. - Type checking is the activity of ensuring that the operands of an operator are of compatible types. - A compatible type is one that is either legal for the operator or is allowed under language rules to be implicitly converted, by compiler- generated code, to a legal type – This automatic conversion is called coercion. - A type error is the application of an operator to an operand of an inappropriate type. - If all type bindings are static, nearly all type checking can be static. - If type bindings are dynamic, type checking must be dynamic. - A programming language is strongly typed if type errors are always detected. - Advantage of strong typing: allows the detection of the misuses of variables that result in type errors. Strong Typing - Language examples: o C and C++ are not: parameter type checking can be avoided; unions are not type checked. o Ada is, almost (UNCHECKED CONVERSION is loophole) (Java and C# are like Ada) - Coercion rules strongly affect strong typing--they can weaken it considerably (C++ versus Ada). - Although Java has just half the assignment coercions of C++, its strong typing is still far less effective than that of Ada. Name Type Equivalence - Name type equivalence means the two variables have equivalent types if they are in either the same declaration or in declarations that use the same type of name. - Easy to implement but highly restrictive: o Subranges of integer types are not equivalent with integer types. o Formal parameters must be the same type as their corresponding actual parameters. Structure Type Equivalence - Structure type equivalence means that two variables have equivalent types if their types have identical structures. - More flexible, but harder to implement. - the problem of two structured types: o With structural type equivalence, you cannot differentiate between types of the same structure. (e.g., different units of speed, both float) Theory and Data Types - Type theory is a broad area of study in mathematics, logic, computer science, and philosophy. - Two branches of type theory in computer science: o Practical – data types in commercial languages. o Abstract – typed lambda calculus - A type system is a set of types and the rules that govern their use in programs. - The formal model of a type system is a set of types and a collection of functions that define the type rules. o Either an attribute grammar or a type of map could be used for the functions o Finite mappings – model arrays and functions. o Cartesian products – model tuples and records. o Set unions – model union types. o Subsets – model subtypes Made by: Abrar

Use Quizgecko on...
Browser
Browser