0% found this document useful (0 votes)
62 views82 pages

ControlStructures LoopsConditionalsAndCaseStatements PDF

Uploaded by

krishna2meet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views82 pages

ControlStructures LoopsConditionalsAndCaseStatements PDF

Uploaded by

krishna2meet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

Programming Languages

Session 3 – Main Theme


Control Structures:
Loops, Conditionals, and Case Statements

Dr. Jean-Claude Franchitti

New York University


Computer Science Department
Courant Institute of Mathematical Sciences

Adapted from course textbook resources


Programming Language Pragmatics (3rd Edition)
Michael L. Scott, Copyright © 2009 Elsevier

1
Agenda

1 Session Overview

2 Control Structures: Loops, Conditionals, and Case Statements

3 Conclusion

2
What is the course about?

 Course description and syllabus:


» http://www.nyu.edu/classes/jcf/CSCI-GA.2110-001
» http://www.cs.nyu.edu/courses/summer14/CSCI-GA.2110-
001/index.html

 Textbook:
» Programming Language Pragmatics (3rd Edition)
Michael L. Scott
Morgan Kaufmann
ISBN-10: 0-12374-514-4, ISBN-13: 978-0-12374-514-4, (04/06/09)

 Additional References:
» Osinski, Lecture notes, Summer 2008
» Barrett, Lecture notes, Fall 2008
» Gottlieb, Lecture notes, Fall 2009
» Grimm, Lecture notes, Spring 2010
3
Session Agenda

 Session Overview
 Control Structures: Loops, Conditionals, and Case Statements
 Conclusion

4
Icons / Metaphors

Information

Common Realization

Knowledge/Competency Pattern

Governance

Alignment

Solution Approach

55
Session 2 Review

 Use of Types
 Name, Scope, and Binding
 Names
 Binding
 Early vs. Late Binding Time Advantages Detailed
 Lifetimes
 Lifetime and Storage Management
 Garbage Collection
 Scopes
 Scope Rules
 Scope Rules – Example: Static vs. Dynamic
 The Meaning of Names within a Scope
 Bindings of Referencing Environments
 Separate Compilation
 Conclusions

6
Agenda

1 Session Overview

2 Control Structures: Loops, Conditionals, and Case Statements

3 Conclusion

7
Control Structures: Loops, Conditionals, and Case Statements

 Control Flow
 Control Structures
 Statement Grouping
 Expression Evaluation
 Sequencing
 Semicolons
 Selection
 Lists / Iteration
 Recursion
 Conclusions

8
Control Flow (1/3)

 Basic paradigms for control flow:


» Sequencing
» Selection
» Iteration
» Procedural Abstraction
» Recursion
» Concurrency
» Exception Handling and Speculation
» Nondeterminacy

9
Control Flow (2/3)

 Structured vs. Unstructured Flow


» Early languages relied heavily on
unstructured flow, especially goto’s.
» Common uses of goto have been captured
by structured control statements.
• Fortran had a DO loop, but no way to exit early
except goto
• C uses break for that purpose

10
Control Flow (3/3)

 The Infamous Goto


» In machine language, there are no if statements or loops
» We only have branches, which can be either unconditional or
conditional (on a very simple condition)
» With this, we can implement loops, if statements, and case
statements. In fact, we only need
• 1. increment
• 2. decrement
• 3. branch on zero
• to build a universal machine (one that is Turing complete).
» We don’t do this in high-level languages because unstructured
use of the goto can lead to confusing programs. See “Go To
Statement Considered Harmful” by Edgar Dijkstra

11
Control Structures (1/2)

 A control structure is any mechanism that departs from


the default of straight-line execution.
» selection
• if statements
• case statements
» iteration
• while loops (unbounded)
• for loops
• iteration over collections
» other
• goto
• call/return
• exceptions
• continuations

12
Control Structures (2/2)

 In assembly language, (essentially) the only


control structures are:
» Progression: Move to the next statement (increment
the program counter).
» Unconditional jump:
JMP A Jump to address A
» Conditional jump:
JMZ R,A If (R==0) then jump to A

Possible forms of conditions and addresses


vary.

13
Statement Grouping

 Many languages provide a way to group several


statement together
 PASCAL introduces begin-end pair to mark sequence
 C/C++/JAVA abbreviate keywords to { }
 ADA dispenses with brackets for sequences, because
keywords for the enclosing control structure are
sufficient
 for J in 1..N loop ... end loop
» More writing but more readable
 Another possibility – make indentation significant (e.g.,
ABC, PYTHON, HASKELL)

14
Expression Evaluation (1/15)

 Languages may use various notation:


» prefix : (+ 1 2) – Scheme
» postfix : 0 0 moveto – Postscript
» infix : 1 + 2 – C/C++, Java
 Infix notation leads to some ambiguity:
» associativity : how operators of the same
precedence are grouped
• – x + y - z = (x + y) - z or x + (y - z) ?
» precedence : the order in which operators are
applied
• – x + y * z = (x + y) * z or x + (y * z) ?
15
Expression Evaluation (2/15)

 Infix, prefix operators


 Precedence, associativity (see Figure 6.1)
» C has 15 levels - too many to remember
» Pascal has 3 levels - too few for good
semantics
» Fortran has 8
» Ada has 6
• Ada puts and & or at same level
» Lesson: when unsure, use parentheses!

16
Expression Evaluation (3/15)

Figure 6.1 Operator precedence levels in Fortran, Pascal, C, and Ada. The operator s at the top of the figure group most tightly.
17
Expression Evaluation (4/15)

 Ordering of operand evaluation (generally


none)
 Application of arithmetic identities
» distinguish between commutativity, and
(assumed to be safe)
» associativity (known to be dangerous)
(a + b) + c works if a~=maxint and b~=minint and c<0
a + (b + c) does not

» inviolability of parentheses

18
Expression Evaluation (5/15)

 Short-circuiting
»Consider (a < b) && (b < c):
• If a >= b there is no point evaluating
whether b < c because (a < b) && (b
< c) is automatically false
»Other similar situations
if (b != 0 && a/b == c) ...
if (*p && p->foo) ...
if (f || messy()) ...

19
Expression Evaluation (6/15)

 Variables as values vs. variables as


references
» value-oriented languages
• C, Pascal, Ada
» reference-oriented languages
• most functional languages (Lisp, Scheme, ML)
• Clu, Smalltalk
» Algol-68 kinda halfway in-between
» Java deliberately in-between
• built-in types are values
• user-defined types are objects - references
20
Expression Evaluation (7/15)

 Expression-oriented vs. statement-


oriented languages
» expression-oriented:
• functional languages (Lisp, Scheme, ML)
• Algol-68
» statement-oriented:
• most imperative languages
» C kinda halfway in-between (distinguishes)
• allows expression to appear instead of statement

21
Expression Evaluation (8/15)

 Orthogonality
» Features that can be used in any
combination
• Meaning is consistent
if (if b != 0 then a/b == c else false) then ...
if (if f then true else messy()) then ...

 Aggregates
» Compile-time constant values of user-defined
composite types

22
Expression Evaluation (9/15)

 Initialization
» Pascal has no initialization facility (assign)
» Assignment statements provide a way to set a value of a
variable.
» Language may not provide a way to specify an initial value.
This can lead to bugs.
» Some languages provide default initialization.
• C initializes external variables to zero
» System may check dynamically if a variable is uninitialized
• IEEE floating point uses special bit pattern (NaN)
• Requires hardware support and expensive software checking
» Compiler may statically check – Java, C#
• May be overly conservative
» OO-languages use constructors to initialize dynamically
allocated variables

23
Expression Evaluation (10/15)

 Assignment
» statement (or expression) executed for its side effect
» assignment operators (+=, -=, etc)
• handy
• avoid redundant work (or need for optimization)
• perform side effects exactly once
» C --, ++
• postfix form

24
Expression Evaluation (11/15)

 Side Effects
» often discussed in the context of functions
» a side effect is some permanent state change
caused by execution of function
• some noticable effect of call other than return
value
• in a more general sense, assignment statements
provide the ultimate example of side effects
– they change the value of a variable
– Side effects change the behavior of subsequent
statements and expressions.

25
Expression Evaluation (12/15)

 SIDE EFFECTS ARE FUNDAMENTAL


TO THE WHOLE VON NEUMANN
MODEL OF COMPUTING

 In (pure) functional, logic, and dataflow


languages, there are no such changes
» These languages are called SINGLE-
ASSIGNMENT languages

26
Expression Evaluation (13/15)

 Several languages outlaw side effects for


functions
» easier to prove things about programs
» closer to Mathematical intuition
» easier to optimize
» (often) easier to understand
 But side effects can be nice
» consider rand()

27
Expression Evaluation (14/15)

 Side effects are a particular problem if


they affect state used in other parts of the
expression in which a function call
appears
» It's nice not to specify an order, because it
makes it easier to optimize
» Fortran says it's OK to have side effects
• they aren't allowed to change other parts of the
expression containing the function call
• Unfortunately, compilers can't check this
completely, and most don't at all
28
Expression Evaluation (15/15)

 There is a difference between the container for a value


(”memory location”) and the value itself.
» l-value refers to the locations. (They are on the left hand side.)
» r-value refers to the values.
• 3 = x + 1 – Illegal! ”3” Can’t be an l-value
• x = x + 1 – x is both an l-value and an r-value
 Imperative languages rely on side effects
» Some languages introduced assignment operators.
» Consider a[f(i)] += 4
• More convenient than a[f(i)] = a[f(i)] + 4
• Ensures that f(i) is evaluated once
 Some languages allow multiway assignment:
» a,b,c = getabc() – Python, Perl

29
Sequencing

 Sequencing
»specifies a linear ordering on
statements
• one statement follows another
»very imperative, Von-Neuman

30
Sequencing

 Pascal: begin … end


 C, C++, Java: { … }
 Ada: Brackets for sequence are
unnecessary. Keywords for control
structures suffice.
for J in 1 .. N loop … end loop
 ABC, Python: Indicate structure by
indentation.

31
Semicolons

 Pascal: Semicolons are separators


 C etc.: Semicolons are terminators

begin X := 1; { X = 1;
Y := 2 Y = 2;
end }

32
Selection (1/13)

 Selection
»sequential if statements
if ... then ... else
if ... then ... elsif ... else
(cond
(C1) (E1)
(C2) (E2)
...
(Cn) (En)
(T) (Et)
)
33
Selection (2/13)

 if Condition then Statement – PASCAL, ADA


 if (Condition) Statement – C/C++, JAVA
 To avoid ambiguities, use end marker: end if, “}”
 To deal with multiple alternatives, use keyword or
bracketing:
if Condition then
Statements
elsif Condition then
Statements
else
Statements
end if;

34
Selection (3/13)

 Nesting and the infamous “dangling else” problem:

if Condition1 then
if Condition2 then
Statements1
else
Statements2
 The solution is to use end markers. In Ada:

if Condition1 then
if Condition2 then
Statements1
end if;
else
Statements2
end if;

35
Selection (4/13)

 Selection
» Fortran computed gotos
» jump code
• for selection and logically-controlled loops
• no point in computing a Boolean value into a
register, then testing it
• instead of passing register containing Boolean out of
expression as a synthesized attribute, pass inherited
attributes INTO expression indicating where to jump
to if true, and where to jump to if false

36
Selection (5/13)

 Jump is especially useful in the presence


of short-circuiting
 Example (section 6.4.1 of book):

if ((A > B) and (C > D)) or (E <> F) then


then_clause
else
else_clause

37
Selection (6/13)

 Code generated w/o short-circuiting


(Pascal)
r1 := A -- load
r2 := B
r1 := r1 > r2
r2 := C
r3 := D
r2 := r2 > r3
r1 := r1 & r2
r2 := E
r3 := F
r2 := r2 $<>$ r3
r1 := r1 $|$ r2
if r1 = 0 goto L2
L1: then_clause -- label not actually used
goto L3
L2: else_clause
L3:

38
Selection (7/13)

 Code generated w/ short-circuiting (C)


r1 := A
r2 := B
if r1 <= r2 goto L4
r1 := C
r2 := D
if r1 > r2 goto L1
L4: r1 := E
r2 := F
if r1 = r2 goto L2
L1: then_clause
goto L3
L2: else_clause
L3:

39
Selection (8/13)

 Short-Circuit Evaluation
if (x/y > 5) { z = ... } // what if y == 0?
if (y == 0 || x/y > 5) { z = ... }
 But binary operators normally evaluate both
arguments. Solutions:
» a lazy evaluation rule for logical operators (LISP, C)
C1 && C2 // don’t evaluate C2 if C1 is false
C1 || C2 // don’t evaluate C2 if C1 is true
» a control structure with a different syntax (ADA)
-- don’t evaluate C2
if C1 and then C2 then -- if C1 is false
if C1 or else C2 then -- if C1 is true

40
Selection (9/13)

 Multi-way Selection
» Case statement needed when there are many
possibilities “at the same logical level” (i.e. depending
on the same condition)
case Next_Char is
when ’I’ => Val := 1;
when ’V’ => Val := 5;
when ’X’ => Val := 10;
when ’C’ => Val := 100;
when ’D’ => Val := 500;
when ’M’ => Val := 1000;
when others => raise Illegal_Roman_Numeral;
end case;
 Can be simulated by sequence of if-statements,
but logic is obscured
41
Selection (10/13)

 Ada Case Statement:


» no flow-through (unlike C/C++)
» all possible choices are covered
• mechanism to specify default action for choices not given
explicitly
» no inaccessible branches:
• no duplicate choices (C/C++, ADA, JAVA)
» choices must be static (ADA, C/C++, JAVA, ML)
» in many languages, type of expression must be
discrete (e.g. no floating point)

42
Selection (11/13)

 Implementation of Case:
» A possible implementation for C/C++/JAVA/ADA style
case (if we have a finite set of possibilities, and the
choices are computable at compile-time):
• build table of addresses, one for each choice
• compute value
• transform into table index
• get table element at index and branch to that address
• execute
• branch to end of case statement
» This is not the typical implementation for a
ML/HASKELL style case

43
Selection (12/13)

 Complications
case (x+1) is
when integer’first..0 ) Put_Line ("negative");
when 1 ) Put_Line ("unit");
when 3 | 5 | 7 | 11 ) Put_Line ("small prime");
when 2 | 4 | 6 | 8 | 10 ) Put_Line ("small even");
when 21 ) Put_Line ("house wins");
when 12..20 | 22..99 ) Put_Line ("manageable");
when others ) Put_Line ("irrelevant");
end case;
 Implementation would be a combination of tables and if
statements

44
Selection (13/13)

 Unstructured Flow (Duff’s Device)

void send (int *to, int *from, int count) {


int n = (count + 7) / 8;
switch (count % 8) {
case 0: do { *to++ = *from++;
case 7: *to++ = *from++;
case 6: *to++ = *from++;
case 5: *to++ = *from++;
case 4: *to++ = *from++;
case 3: *to++ = *from++;
case 2: *to++ = *from++;
case 1: *to++ = *from++;
} while (--n > 0);
}
45
Iteration / Loops (1/14)

 Enumeration-controlled
»Pascal or Fortran-style for loops
• scope of control variable
• changes to bounds within loop
• changes to loop variable within loop
• value after the loop

46
Iteration / Loops (2/14)

 Indefinite Loops
» All loops can be expressed as while-loops
• good for invariant/assertion reasoning
» condition evaluated at each iteration
» if condition initially false, loop is never executed
while condition loop ... end loop;
is equivalent to
if condition then
while condition loop ... end loop
end if;
if condition has no side-effects

47
Iteration / Loops (3/14)

 Executing While at Least Once


» Sometimes we want to check condition at end instead of at
beginning; this will guarantee loop is executed at least once.
• repeat ... until condition; (PASCAL)
• do { ... } while (condition); (C)
» while form is most common can be simulated by while + a
boolean variable:

first := True;
while (first or else condition) loop
...
first := False;
end loop;

48
Iteration / Loops (4/14)

 Breaking Out
» A more common need is to be able to break out of
the loop in the middle of an iteration.
• break (C/C++, JAVA)
• last (PERL)
• exit (ADA)
loop
... part A ...
exit when condition;
... part B ...
end loop;

49
Iteration / Loops (5/14)

 Breaking Way Out


» Sometimes, we want to break out of several levels of a nested
loop
• give names to loops (ADA, PERL)
• use a goto (C/C++)
• use a break + lable (JAVA)

Outer: while C1 loop ...


Inner: while C2 loop ...
Innermost: while C3 loop ...
exit Outer when Major_Failure;
exit Inner when Small_Annoyance;
...
end loop Innermost;
end loop Inner;
end loop Outer;

50
Iteration / Loops (6/14)

 Definite Loops
» Counting loops are iterators over discrete domains:

• for J in 1..10 loop ... end loop;


• for (int i = 0; i < n; i++) { ... }

» Design issues:

• evaluation of bounds (only once, since ALGOL 60)


• scope of loop variable
• empty loops
• increments other than 1
• backwards iteration
• non-numeric domains

51
Iteration / Loops (7/14)

 Evaluation of Bounds

for J in 1..N loop


...
N := N + 1;
end loop; -- terminates?

» Yes – in ADA, bounds are evaluated once before iteration starts. Note:
the above loop uses abominable style. C/C++/JAVA loop has hybrid
semantics:

for (int j = 0; j < last; j++) {


...
last++; -- terminates?
}

» No – the condition “j < last” is evaluated at the end of each iteration

52
Iteration / Loops (8/14)

 The Loop Variable


» is it mutable?
» what is its scope? (i.e. local to loop?)

 Constant and local is a better choice:


» constant: disallows changes to the variable, which can affect the
loop execution and be confusing
» local: don’t need to worry about value of variable after loop exits

Count: integer := 17;


...
for Count in 1..10 loop
...
end loop;
... -- Count is still 17

53
Iteration / Loops (9/14)

 Different Increments
ALGOL 60:

for j from exp1 to exp2 by exp3 do ...

» too rich for most cases; typically, exp3 is +1 or -1.


» what are semantics if exp1 > exp2 and exp3 < 0?

C/C++:

for (int j = exp1; j <= exp2; j += exp3) ...

ADA:

for J in 1..N loop ...


for J in reverse 1..N loop ...

Everything else can be programmed with a while loop

54
Iteration / Loops (10/14)

 Non-Numeric Domains
ADA form generalizes to discrete types:

for M in months loop ... end loop;

Basic pattern on other data types:

» define primitive operations: first, next, more_elements


» implement for loop as:

iterator = Collection.Iterate();
element thing = iterator.first;
for (element thing = iterator.first;
iterator.more_elements();
thing = iterator.next()) {
...
}

55
Iteration / Loops (11/14)

 List Comprehensions

» PYTHON calls them “generator expressions”


» Concise syntax for generating lists
» Example:
l = [1,2,3,4]
t = ’a’, ’b’
c1 = [x for x in l if x % 2 == 0]
c2 = [(x,y) for x in l if x < 3 for y in t]
print str(c1) # [2,4]
print str(c2) # [(1, ’a’),(1, ’b’),(2, ’a’),(2, ’b’)]

» Shorthand for:

c2 = [ ]
for x in l:
if x < 3:
for y in t:
c2.append((x,y))

56
Iteration / Loops (12/14)

57
Iteration / Loops (13/14)

 Efficient Exponentiation

function Exp (Base: Integer;


Expon: Integer) return Integer is
N: Integer := Expon; -- successive bits of exponent
Res: Integer := 1; -- running result
Pow: Integer := Base; -- successive powers: Base2I
begin
while N > 0 loop
if N mod 2 = 1 then
Res := Res * Pow;
end if;
Pow := Pow * Pow;
N := N / 2;
end loop;
return Res;
end Exp;

58
Iteration / Loops (14/14)

59
Recursion (1/3)

 Recursion
»equally powerful to iteration
»mechanical transformations back and
forth
»often more intuitive (sometimes less)
»naïve implementation less efficient
• no special syntax required
• fundamental to functional languages like
Scheme
60
Recursion (2/3)

 Tail recursion
» No computation follows recursive call
• In this case we do not need to keep multiple copies of the local
variables since, when one invocation calls the next, the first is
finished with its copy of the variables and the second one can
reuse them rather than pushing another set of local variables on
the stack. This is very helpful for performance.
int gcd (int a, int b) {
/* assume a, b > 0 */
if (a == b) return a;
else if (a > b) return gcd (a - b,b);
else return gcd (a, b – a);
}
61
Recursion (3/3)

 Iterative version of the previous program:


int gcd (int a, int b) {
/* assume a, b > 0 */
start:
if (a == b) return a;
if (a > b) {
a = a-b;
goto start;
}
b = b-a;
goto start;
} 62
Appendix

1 APL

2 Ada95

3 J

4 Perl

5 Python

63
History

 Developed by Kenneth Iverson in the early


1960’s
 Tool for mathematicians
» Tool for thought
» Way of thinking
» Very high level language for matrix
manipulation
 Widely used by actuaries in Insurance
 Use restricted by special character set
including greek letters and other symbols

64
Typing and Scope

 Dynamic Scope
 Two Types – Numbers and Characters
» Automatic conversion between floating point and
integer
» Strings are character vectors
» Boolean values are 0 and 1
 Type associated with Values, not names
» Tagged types
» Run-time checking

65
Example

 An APL program to find all prime numbers


<= an integer
(http://www.users.cloud9.net/~bradmcc/AP
L.html) :
PRIMES : (~R∈R○.×R)/R←1↓ιR

66
Example (continued)

 This line of code calculates the prime numbers from 2 to the starting
value of R, in this example 20.
 the "iota funtion" of R filles a vector (and that will be R again) with
numbers from 1 to the value of the variable (20 in this example), the
first element is dropped (that is the 1); so to the right of the "/" there
will be 2 3 4 5 ... 18 19 20
 the "small.circle-dot-multiply" defines an outer product so all
elements of R are multiplied by all elements of R giving a matrix;
check whether elements of R are in the matrix and make a vector
containing "1"-s at the place where that is true and "0"-s where that
is not true
 inverse that vector and use it to grab that elements from R using the
"over" function

67
Syntax

 Simple syntax
» Right to left evaluation
» infix operators and functions
» modifiers (verbs and adverbs)
• Modifiers are operators that modify the operation of other operators
» Can be parsed with only 3 states (Zaks)
 Expression Language
» No selection or looping statements
» Only goto
 Scalar operators automatically extend to
matrices
» Loops are unusual in APL

68
Operations on numbers

Monadic
 ⌈B, ⌊B -- ceiling/floor
⌈3.4 = 4

{floor} {minimum} (⌊ symbol)


{floor}B returns the largest integer that is less than or equal to B. (For positive numbers, this is usually the integer part of B.)
The dyadic form, A{minimum}B, returns the lesser of A and B. To find the smallest element in a vector, {minimum} is used with the reduce operator, as
in {minimum}/B.

{ceiling} {maximum} (⌈ symbol)


{ceiling}B returns the smallest integer that is greater than or equal to B. (For positive numbers, this rounds B up to the next higher integer.)
The dyadic form, A{maximum}B, returns the greater of A and B. To find the largest element in a vector, {maximum} is used with the reduce operator, as in {maximum}/B.

{quotequad} (square with quote symbol)


{quotequad} is used for character input and output. Assigning a value to {quotequad}, as in {quotequad}{<-}B, causes the value of B to be displayed (without a carriage
return being appended at the end). Referencing {quotequad}, as in Z{<-}{quotequad}, causes a line of character input to be read from the user.

Dyadic
 A⌈B, A⌊B -- max, min
A⌈B returns maximum of x or y 2⌈3=3
{ln} {log} (circled start symbol)
{ln}B returns the natural log of B. A{log}B returns the base-A log of B.

69
Operations on Arrays

  -- interval
n returns a vector of integers from origin to n
4 = 1 2 3 4
  -- size 0 1 2 3 = 4
 Dyadic
 -- shape
reshapes an array
2 20 1 2 3 creates a 2 x 2 array
  -- Transpose
Rotates an array along the major diagonal
  -- Domino
Does matrix inversion and division

70
Operations on Arrays (continued)

 {drop} - (down arrow symbol)


A{drop}B returns a copy of vector B without the first A (if A>0) or last A (if A<0) elements. If B is a matrix, A is must
be two numbers, with A[1] giving the number of rows and A[2] giving the number of columns to drop.

 {take} – (up arrow symbol)


A{take}B returns the first A (if A>0) or last A (if A<0) elements of a vector B. If B is a matrix, A is must be two
numbers, with A[1] giving the number of rows and A[2] giving the number of columns to return.

 {epsilon} {enlist} {membership} (epsilon symbol)


A{membership}B returns a Boolean array having the same shape as A. Ones in the result mark elements of A that
occur in B; zeros mark elements that don't occur in B.
The monadic form, {enlist}B, flattens and ravels a nested array. It returns a simple (non-nested) vector containing
all the elements in B.

 {gradeup} (triangular up arrow symbol)


{gradeup}B returns a permutation vector that describes how to arrange the elements of a numeric vector B in
ascending order. The expression B[{gradeup}B] can be used to obtain a sorted copy of B.
The dyadic form, A{gradeup}B, is used for character data. The left argument (A) specifies the collating sequence.
If B is a matrix, the result describes how to arrange the rows in alphabetic order. B[{gradeup}B;] returns a sorted
copy of B.

 {transpose} (empty set symbol)


{transpose}B returns the transpose of a matrix B. (It flips the matrix across the main diagonal, so the first row
becomes the first column.) More generally, transpose reverses the order of the dimensions in B. Consequently, it
has no effect on vectors or scalars.
The dyadic form, A{transpose}B, reorders the dimensions of B according to A. If A is a permutation vector (i.e., if it
has no duplicate elements), the shape of the result Z is related to the shape of B by the identity ({shape}Z)[A] <-->
{shape}B.
If A has duplicate elements, transpose takes a diagonal slice along the dimensions corresponding to the
duplicated elements. The most common case of this form is 1 1{transpose}B, which returns the main diagonal of a
matrix B.

71
Operators on Operators

 .+ -- outer product


1 2 .+ 3 4
45
56
 +. -- inner product
1 2 +. 3 4 – matrix multiplication
7 14
 +/ -- reduction +/2 3 4 = 9
equivalent to 2 + 3 + 4
 +\ -- scan +\2 3 4 = 2 5 9
like reduction, but with intermediate results
^\ 0 0 1 0 1 = 0 0 1 1 1 -- turns on all bits after first 1
 Any dyadic operator can be used for + or 

72
Appendix

1 APL

2 Ada95

3 J

4 Perl

5 Python

73
Ada95

 Overview of Ada95
» http://cs.nyu.edu/courses/fall01/G22.2110-
001/pl.lec3.ppt
 Ada Summary
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/AdaIntro.html
 Notes on Ada
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/AdaNotes.html
 Syntax of Ada95:
» http://www.cs.nyu.edu/courses/fall05/G22.2110-
001/RM-P.html

74
Appendix

1 APL

2 Ada95

3 J

4 Perl

5 Python

75
J

 See
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/JDictionary.pdf

76
Appendix

1 APL

2 Ada95

3 J

4 Perl

5 Python

77
Perl

 See
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/PrototypingInPerl.pdf

78
Appendix

1 APL

2 Ada95

3 J

4 Perl

5 Python

79
Python

 Introduction to Python
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/PythonIntro.pdf
 Python Summary
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/PythonSummary.pdf
 Notes on Python
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/PythonNotes.html

80
Assignments & Readings

 Readings
» Chapter Sections 6.1-6.5
 Programming Assignment:
» See Programming Assignment #1 posted under “handouts” on the
course Web site
» Due on July 3, 2014

81
Next Session:

 Subprograms:
» Functions and Procedures
» Parameter Passing
» Nested Procedures
» First-Class and Higher-Order Functions

82

You might also like