CH 6
CH 6
GLOBAL EDITION
Chapter 6
Data Types
• Simplest of all
• Range of values: two elements, one for
“true” and one for “false”
• Could be implemented as bits, but often as
bytes
– Advantage: readability
• Typical operations:
– Assignment and copying
– Comparison (=, >, etc.)
– Catenation
– Substring reference
– Pattern matching
• Aid to writability
• As a primitive type with static length, they
are inexpensive to provide--why not have
them?
• Dynamic length is nice, but is it worth the
expense?
Compile-time Run-time
descriptor for descriptor for
static strings limited dynamic
strings
Copyright © 2023 Pearson Education Ltd. All Rights Reserved. 1-17
User-Defined Ordinal Types
• C-based languages
– int list [] = {1, 3, 5, 7}
– char *names [] = {″Mike″, ″Fred″, ″Mary Lou″};
• Python
– List comprehensions
list = [x ** 2 for x in range(12) if x % 3 == 0]
puts [0, 9, 36, 81] in list
• Python
vector = [2, 4, 6, 8, 10, 12, 14, 16]
mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
• 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;
(The asterisk is just a separator)
• F#
let tup = (3, 5, 7)
let a, b, c = tup
This assigns a tuple to a tuple pattern (a, b, c)
• List Operations 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, ::
3 :: [5, 7, 9] evaluates to [3, 5, 7, 9]
– The Scheme CAR and CDR functions are named hd
and tl, respectively
• F# Lists
– Like those of ML, except elements are separated
by semicolons and hd and tl are methods of the
List class
• Python Lists
– 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
myList = [3, 5.8, "grape"]
| …
Example:
let a = 7;;
let b = ″grape″;;
let x = match (a, b) with
| 4, ″apple″ -> apple
| _, ″grape″ -> grape
| _ -> fruit;;
float stuff[100];
float *p;
p = stuff;
int? x;
Language examples:
– C and C++ are not: parameter type checking
can be avoided; unions are not type checked
– Java and C# are, almost (because of explicit type
casting)
- ML and F# are