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

Combinepdf

The document provides examples of variable scope and dynamic/static typing in various programming languages including C, C++, Dart, JavaScript, Perl, PHP, and Python. It illustrates concepts like explicit heap dynamics, static variables, and the behavior of local and global variables within functions and blocks. The examples demonstrate how different languages handle variable scoping and the implications of using local versus global variables.

Uploaded by

atakanakargs190
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)
7 views82 pages

Combinepdf

The document provides examples of variable scope and dynamic/static typing in various programming languages including C, C++, Dart, JavaScript, Perl, PHP, and Python. It illustrates concepts like explicit heap dynamics, static variables, and the behavior of local and global variables within functions and blocks. The examples demonstrate how different languages handle variable scoping and the implications of using local versus global variables.

Uploaded by

atakanakargs190
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

C Examples

Explicit heap dynamic 1

Explicit heap dynamic


Static variable

C++ Examples
Explicit Heap Dynamic 1
Explicit heap dynamic

Dart Examples
Array

Enumeration
Fibonacci

Hello World

List

Print Integer
t1

Test

Type inferencing dynamic


Type inferencing static

Type inferencing

Type inferencing 2
JavaScript Examples
Console

Dynamic Types

Running

Vars
Perl Examples
Ex1
Chapter 5 Scope
C
main() { In main i=1

int i=1; In outer block i=2

printf("In main i=%d\n", i); In inner block i=3

{ // outer block In outer block i=2

int i=2; In main i=1

printf("In outer block i=%d\n", i);

{ // inner block

int i=3;

printf("In inner block i=%d\n", i);

————————————————————————————————————————————————————————--
#include<stdio.h> In sub3, x=1, y=2, z=3

void sub1() { In sub2, x=1, y=2

int x; In sub1, x=1

void sub2() {

int y;

void sub3() {

int z = 3;

printf("In sub3, x=%d, y=%d, z=%d\n", x, y, z);

} // sub3

y = 2;

sub3();

printf("In sub2, x=%d, y=%d\n", x, y);

} // sub2

x = 1;

sub2();

printf("In sub1, x=%d\n", x);

} // sub1

void main() {

sub1();

}
#include<stdio.h>
in foo: n=5
void foo() {
in bar: i=7
static int n = 5;
in foo: n=6
printf("in foo: n=%d\n", n);

n++;

} // foo

void bar() {

static int n = 7;

printf("in bar: i=%d\n", n);

void main() {

foo();

bar();

foo();

} // main

————————————————————————————————————————————————————————--

JavaScript
x=5;

{ // let is block scoped x in the block: 3

let x = 3; x in global: 5

console.log("x in the block: "+x);

console.log("x in global: "+x);

————————————————————————————————————————————————————————--

x=5;
x=3
{ // var does not create local
scope for its variables in the
block.

var x = 3;

console.log("x="+x);
function sub1() {

var x;

function sub2() { x=1 y=2 z=3

var y; x=1 y=2

function sub3() {

var z;

z=3;

console.log("x=" + x + " y=" + y + " z=" + z);

} // sub3

y=2;

sub3();

console.log("x=" + x + " y=" + y);

} // sub2

x = 1;

sub2();

} //sub1

sub1()

————————————————————————————————————————————————————————--

x = 1; in foo, x=3
function foo() { in global x=1
var x = 3; // try with/without "var"

console.log("in foo, x="+x);

foo();

console.log("in global x="+x);

————————————————————————————————————————————————————————--

x = 1; in foo, x=3
function foo() { in global x=3
x = 3; // try with/without "var"

console.log("in foo, x="+x);

foo();

console.log("in global x="+x);


function foo1() {

var lcl = 5; // local to foo1

glb = 7; // global In foo1, lcl=5, glb=7

console.log("In foo1, lcl="+ lcl + ", glb="+glb); In foo2, lcl=3, glb=7

function foo2() {

var lcl = 3; // local to foo2

console.log("In foo2, lcl="+ lcl + ", glb="+glb);

}
————————————————————————————————————————————————————————--
x=5;

function foo () { console.log("in foo, x="+x);


console.log("in foo, x="+x); ^
x = 7;

console.log("in foo, x="+x); ReferenceError: x is not defined


let x; // local variable x is defined at the end of the function
definition !

// Hoisting: all let declaration are executed as the first


statements of their scope.

// but are NOT initialized

foo();

console.log("in global x="+x);

————————————————————————————————————————————————————————--
x=5;

function foo () { in foo, x=undefined


console.log("in foo, x="+x); in foo, x=7
x = 7; in global x=5
console.log("in foo, x="+x);

var x; // local variable x is defined at the end of the function


definition !

// Hoisting: all var declaration are executed as the first


statements of their scope.

// and initialized to 'undefined'

foo();

console.log("in global x="+x);


function foo (a) {

console.log("foo is called, a="+a);

x = a; // a global varible is defined


foo is called, a=5
var y = a * 2; // a local variable is defined
in global, y= 10
/*
in global, x= 5
The scope of a variable declared with var is its current
5
execution context,
End of the code
which is either the enclosing function or, for variables
declared outside

any function, global. */

console.log("in global, y=", y);

foo(5);

console.log("in global, x=", x);

console.log(x);

// console.log("in global, y=", y);

console.log("End of the code"); // Press F12 to see the


messages sent to the console

————————————————————————————————————————————————————————--
x=5;

n=1; x=5 m=77 n=0

while (n==1) {

var m= 77; // try with let in the place of var

n=0;

console.log("x="+x+" m="+m+" n="+n);

————————————————————————————————————————————————————————--

x=5;

n=1;

while (n==1) { ReferenceError: m is not defined

var m= 77; // try with let in the place of var

n=0;

console.log("x="+x+" m="+m+" n="+n);


Perl
$a = 0; # global variable

sub foo {
in foo, a is 0
return "in foo, a is $a\n";
in bar, b is 1
}
global b is 77
sub staticScope {

my $a = 1; # lexical (static), local to staticScope function

return foo();

print staticScope(); # 0 (from the saved global frame)

$b = 0; # global variable

sub bar {

return "in bar, b is $b\n";

sub dynamicScope {

$b =77;

local $b = 1;

return bar();

print dynamicScope(); # 1 (from the caller's frame)

print "global b is $b\n";

————————————————————————————————————————————————————————--
sub visible {

print "var has the value $var\n";}

sub dynamic {
var has the value global
local $var = 'local'; # new temporary value for the still-global var has the value local
visible(); # variable called $var var has the value global

sub lexical {

my $var = 'private'; # new private variable, $var is created

visible(); # (invisible outside of sub scope)}

$var = 'global';

visible(); # prints global

dynamic(); # prints local

lexical(); # prints global


$g=5;

sub A { In A: g=7, x=2, y=3


my $x=2; # $x uses static scoping In B: g=7, x=, y=3
In C: g=7, x=, y=3
local $y=3; # $y uses dynamic scoping
In main: g=5, x=, y=
local $g=7;

print "In A: g=$g, x=$x, y=$y\n";

B();

sub B {

print "In B: g=$g, x=$x, y=$y\n";

C();

sub C {

print "In C: g=$g, x=$x, y=$y\n";}

A();

print "In main: g=$g, x=$x, y=$y\n";


————————————————————————————————————————————————————————--
$x = 123;

sub foo {

print "$x\n"; # 123} 456


123
{ local $x = 456;

foo(); # 456}

foo();
————————————————————————————————————————————————————————--

sub static_parent {

print "In static_parent\n";


Can't localize lexical variable $x at
my $x='static-parent'; jdoodle.pl line 11.
sub check {

print "In check, x=$x\n"; }

sub dynamic_parent {

print "in dynamic_parent\n";

local $x='dynamic-parrent'; # Error,

# you can only localize global variables.

check;}

dynamic_parent;}

static_parent;
sub static_parent {

print "In static_parent\n";

my $x='static-parent';

sub check { In static_parent


In check, x=static-parent y= a=
print "In check, x=$x y=$y a=$a\n";
in dynamic_parent
} In check, x=static-parent
y=dynamic-parrent a=global vari-
sub dynamic_parent {
able
print "in dynamic_parent\n"; a is global variable
$a= 'global variable'; x is
y is
local $y='dynamic-parrent';

check;

check;

dynamic_parent;

static_parent;

print "a is $a\n";

print "x is $x\n";

print "y is $y\n";

————————————————————————————————————————————————————————--

sub big {

$var=1;
In global, before big, var is **
sub sub1 () { In sub1, var=1
In sub2, var is 2
print "In sub1, var=$var\n";}
In sub1, var=2
sub sub2 () { In sub1, var=2
$var = 2; In global, after big, var is 2

print "In sub2, var is $var\n";

sub1();

sub1();

sub2();

sub1();

print "In global, before big, var is *$var*\n";

big();

print "In global, after big, var is $var\n";


sub big {
In sub2, var=2
local $var = 1;
In sub1 var=2
sub sub1 () { In sub1 var=1

print " In sub1 var=$var\n";

sub sub2 () {

local $var = 2;

print "In sub2, var=$var\n";

sub1();

sub2();

sub1();

big();

————————————————————————————————————————————————————————--
sub big {

my $var=1;
In global, before big, var=
sub sub1 () { In sub2, var=2
print " In sub1 var=$var\n"; In sub1 var=1
In sub1 var=1
}
In global, after big, var=
sub sub2 () {

my $var = 2;

print "In sub2, var=$var\n";

sub1();

sub2();

sub1();

print "In global, before big, var=$var\n";

big();

print "In global, after big, var=$var\n";


# static-dynamic-scope.pl

# Lexical and dynamic scopes in Perl;

# Static (lexical) scope uses model of

# environments with frames; dynamic scope

# uses single global var frame.

$a = 0; 0
1
sub foo {

return $a;

sub staticScope {

my $a = 1; # lexical (static)

return foo();

print staticScope(); # 0 (from the saved global frame)

print "\n";

$b = 0;

sub bar {

return $b;

sub dynamicScope {

local $b = 1;

return bar();

print dynamicScope(); # 1 (from the caller's frame)

————————————————————————————————————————————————————————--

PHP
<?php

define("SIZE", 5); SIZE=5 $twice is 10

echo "SIZE=".SIZE."\n";

$twice = SIZE * 2;

echo "\$twice is $twice\n";

?>
<?php

echo "Global variables in PHP<br>";

$day ="Monday";

$month = "October";

function calendar() {

$day = "Tuesday";

print "local day is $day <br>";

$gday = $GLOBALS['day'];

print "local gday is $gday <br>";

$GLOBALS['day'] = "Wednesday";
Global variables in PHP
print "gday is $gday.<br>"; local day is Tuesday
local gday is Monday
$month = "April";
gday is Monday.
print "local month is $month<br>"; local month is April
global month is March
In the other block, day is Wednesday
In the other block, month is March
global $month; // affects the rest of block
In the other block, year is 2020
$month = "March";

print "global month is $month<br>";

global $year;

$year=2020;}

calendar();

?>

<?php

echo "In the other block, day is $day<br>";

echo "In the other block, month is $month<br>";

echo "In the other block, year is $year<br>";

?>
————————————————————————————————————————————————————————--
<?php

$x = 5;

$y = 10;
x is
function foo() {
in foo, y is
echo "x is $x<br>"; // $x is not visible in global, y is 5

$GLOBALS['y'] = $GLOBALS['x'] + $y;

echo "in foo, y is $y<br>";

global $y; }

foo();

echo "in global, y is $y<br>";

?>
<!--

The scope of a variable is the context within which it is defined.

For the most part all PHP variables only have a single scope.

It is possible access the global variables

-->
x=
<?php g=3

$g = 3; // a global variable, defined outside of all functions

function foo() {

$x = 7;

function bar() { // nested functions can be defined, but

echo "x=$x <br>"; // the nonlocal variables are not accessible.

global $g;

echo "g=$g <br>"; // the global variables are accessible.

bar();

} // foo

foo();

?>

————————————————————————————————————————————————————————--

Python
day = "Monday"

def calendar(): global day is Monday

print ("global day is", day) # day


is global

calendar()

————————————————————————————————————————————————————————--
day = "Monday"

def calendar(): local day is Tuesday

day = "Tuesday" # day is local, global day is Monday


because of this assignment

print ("local day is", day)

calendar()

print ("global day is", day)


day = "Monday"

def calendar():
UnboundLocalError: local variable 'day'
print ("global day is", day) referenced before assignment
day = "Tuesday" #day becomes local !!! Error

print ("local day is", day)

calendar()

print ("global day is", day)

————————————————————————————————————————————————————————--

day = "Monday"

def calendar():
global day is Monday
global day #day is defined as global
global day is Tuesday
print ("global day is", day)

day = "Tuesday" # this day is global

calendar()

print ("global day is", day)

————————————————————————————————————————————————————————--

day = "Monday"

def calendar(): global day is Monday


global day #day is defined as global global day is Tuesday
print("global day is", day) day in c is Tuesday
day = "Tuesday" # this day is global

print("global day is", day)

def c():

print("day in c is", day)

calendar()

c()
————————————————————————————————————————————————————————--
day = "Monday"

def calendar(): SyntaxError: name 'day' is as-


signed to before global declara-
day = "Newday"
tion
global day #day is defined as global

print ("global day is", day)

calendar()

print ("global day is", day)


def outside():
Inside!
msg = "Outside!"
Outside!
def inside():

msg = "Inside!"

print(msg)

inside()

print(msg)

outside()

————————————————————————————————————————————————————————--
msg = "Global"
Inside!
def outside():
Outside!
msg = "Outside!"
Inside!
def inside():

global msg

msg = "Inside!"

print(msg)

inside()

print(msg)

outside()

print(msg)

————————————————————————————————————————————————————————--
def outside():

msg = "Outside!"
Inside!
def inside():
Inside!
nonlocal msg

msg = "Inside!"

print(msg)

inside()

print(msg)

outside()
msg = "Global"

def outside():
Inside!
msg = "Outside!"
Inside!
def inside():
Global
nonlocal msg

msg = "Inside!"

print(msg)

inside()

print(msg)

outside()

print(msg)

————————————————————————————————————————————————————————--
x=0

def outer():

x=1
inner: 2
def inner():
outer: 2
nonlocal x
global: 0
x=2

print ("inner:", x)

inner()

print ("outer:", x)

outer()

print ("global:", x)

————————————————————————————————————————————————————————--
x=0

def outer(): SyntaxError: no binding for nonlocal 'x'


y=1 found

def inner():

nonlocal x

x=2

print ("inner:", x)

inner()

print ("outer:", x)

outer()

print ("global:", x)
def level1():

x=1

def level2():

y=2 level3: x= 3 y= 2

def level3(): level2: x= 3 y= 2

nonlocal x level1: x= 3

x=3

print ("level3: x=",x, "y=",y)

level3()

print ("level2: x=",x, "y=",y)

level2()

print ("level1: x=",x)

level1()

————————————————————————————————————————————————————————--
def foo ():

print ("in foo:", x) in foo: 7


def bar(): in bar: 7
print("in bar:", x)

bar()

x=7

foo()
————————————————————————————————————————————————————————--
def foo ():

x=5
in main x is 3
def bar():
in foo x is 5
#x=7
in bar x is 5
print("in bar x is", x)
in foo x is 5

in main x is 3
print("in foo x is", x)

bar()

print("in foo x is", x)

x=3

print("in main x is", x)

foo()

print("in main x is", x)


Chapter 6 Code Examples

C Examples
Code arrays.c

Output
foo, sa[0]=0 sa[1]=0 sa[2]=0 sa[3]=33
foo, ehda[0]=0 ehda[4]=44
bar, sda[0]=0 sda[1]=0 sda[2]=22 sda[3]=0
main, sa[0]=3 sa[1]=5 sa[2]=7 sa[3]=9

Code dangling_ptr_explicit.c
Output
p is 0x563867d372a0
q is 0x563867d372a0
after free(q):
q is 0x563867d372a0
p is 0x563867d372a0
is 0x563867d372a0
*p is 7

Code dangling_ptr_implicit.c

Output
*ip is 32765

Code enum.c
Code multi-dim-array.c

Code nested-struct.c
Output
Person2: Name=Ahmet, Age=21, Salary=4567.890137
Person2: Name=Ahmet, Age=22, Salary=4567.890137
Person1: Name=Ahmet, Age=21, Salary=4567.890137

Code stack-array.c

Output
357
468
357

Code static-variable.c
Output
in foo: n=5
in foo: n=5
in bar: i=7
in bar: i=8

Code string.c

Output
97-98-99-0-0-0-0-0-0-0-
97-98-99-100-101-102-0-0-0-0-

Code string_0.c

Output
5th char in Ali is **
Code struct.c

Output
Size of name in person is 50
Size of age in person is 4
Size of salary in person is 4
Size of person is 60
Person2: Name=Ahmet, Age=21, Salary=4567.890137
Person2: Name=Ahmet, Age=22, Salary=4567.890137
Person1: Name=Ahmet, Age=21, Salary=4567.890137
Code union.c

Output
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Memory size of a Data: 20

Code vla.c

Output
In foo, Enter number: In foo, 17
Size of array is 21931
JS Examples
Code associative-array.js

Code associative-array.html

Output
hi32
Perl Examples
Code dynamic-array.pl

Output
Foo Bar Moo
$names[1] = Bar
Foo 30 Moo
Foo 30 Moo Darth Vader
Vader
Foo 30 Moo Darth
Foo
30 Moo Darth
Code grades.pl

Output
grade of Veli: 80
grade of Veli: 90
grade of Su: 100
Su 100
Veli 90
Nur 99
after makint it empty:
PHP Examples
Code array_0.php

Output
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
)
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
[B+] => 3.3
)
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
[B+] => 3.3
[4] => fifth
)
Code array_1.php

Output
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
)
<br>first<br />third<br />
first<br />
Array
(
[0] => 0.2
[1] => 2
[2] => Ahmet
)
Rust Examples
Code array_0.rs

Output
[1, 2, 3, 4, 5]

Code array_1.rs

Output
[1, 2, 3, 4, 5]
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]

Code hello-world.rs

Output
Hello, world!
Code slice.rs

Output
first element of the array: 1
second element of the array: 2
array size: 5
zs is [0, 4, 16, 36, 64]
zs1 is [16, 36, 64]
borrow a section of the array as a slice
first element of the slice: 3
the slice has 3 elements
Python Examples
Code dynamic_array.py

Output
[2, 1.6, (3+5j), 'c', 'a word']
(-7+11j)
['a', 3]
a is ['a', 3, 'q']
first element of a is a
a is ['z', 3, 'q', 'hale', 'jale', 'lale']
a is ['z', 3, 'q', 'jale', 'lale']
last element of a is lale
Code garbage_collect.py

Code garbage_collect_ex.py
Output
2
3
3

Code lists.py

Output
[1, 2.3, 'three']
[1, 'three']
[1, 'orange', 'three']
[1, 'orange', 'three', 'plum']

Code reference-counts.py

Output
2
4
2
Code reference-counts-1.py

Output
4
5
4
5

Code reference-counts-2.py

Output
Code slices.py

Output
[2, 4, 6]
[8, 10, 12, 14, 16]
[2, 4, 6, 'a', 'b', 14, 16]
[[1, 2, 3], [2, 4, 6, 'a', 'b', 14, 16], [7, 8, 9]]
[[1, 2, 3], [2, 4, 6, 'a', 14, 16], [7, 8, 9]]
[11, 33, 55]
[3, 6, 9]

Code tuple.py
Output

Code tuples.py

Output
5.8
[3, 5.8, 'apple']
[3, 6.7, 'apple']
(3, 6.7, 'apple', 1, 'pear')
5
Chapter 7 Code Examples
C Examples
Bitwise-and.c

c.c

coercion.c

float2int.c
functional_side_effect.c

increment.c

short-circuit.c
unary-ops.c

conditional.c
Java Examples
Ex.java
JavaScript Examples
short-circuit.c

Output
in foo !
x = true
Perl Examples
multiple-assignment.pl
Python Examples
conditional.py

fibonacci.py

operator-overloading.py
Ruby Examples
ex.rb
CS 315 Examples 1

Examples for Programming Language Features


Ch 1 Preliminaries
1.3 Language Evaluation Criteria
1.3.3 Reliability
1.3.3.1 Type Checking
The following C program compiles and runs!
foo (float a) {
printf (“a: %g and square(a): %g\n”, a, a*a);
}
main () {
char z = ‘b’;
foo(z);
}
Output is : a: 98 and square(a): 9604

Subscript range checking for arrays is a part of type checking, but it must be done in the run-
time. Out-of-range subscript often cause errors that do not appear until long after actual
violation.
#include <stdio.h>
foo (char s[]) {
printf ("5th char in %s is %c\n", s, s[4]);
}

main () {
char str[] = "abc";
foo(str);
}
produces:
5th char in abc is }

Ch 3. Describing Syntax and Semantics


3.1. Formal Methods of Describing Syntax
Example: Python formal definition
(https://docs.python.org/3/reference/simple_stmts.html)
CS 315 Examples 2

Ch 5. Names, Bindings, and Scopes


5.4.2.1 Static Type Binding
In Perl, $x is a scalar, @x is an array, %x is a hash.

$x = 5;
5
print $x ."\n";
Hello
$x = "Hello";
Hello
print $x ."\n";
Ali Ayse Can Canan
@x = ("Ali", "Ayse", "Can", "Canan");
print "$x \n";
print "@x \n";
%data = ('A', 4.0, 'A-', 3.7, 'B+', 3.3, 'B', 3); 3.7
print "$data{'A-'}\n";

5.4.2.2. Dynamic Type Binding


Javascript uses dynamic type binding.
list = [2, 4.33, 6, 8]; list is a single dimensioned array.
list = 73 list is a simple integer.

5.4.3.1. Static Variables


Ex in C:
int a = 5; // global static variable
int foo(){
static int b = 10; // static variable, scope is only the function.
}

5.4.3.3. Explicit Heap-Dynamic Variables


Ex in C++
int *intnode; // create a pointer
intnode = new int; // create the heap-dynamic variable
delete intnode; // deallocate the heap-dynamic variable
CS 315 Examples 3

Ex in Java:
Integer i = new Integer(5);

5.4.3.4 Implicit Heap-Dynamic Variables


Example in JavaScript:
numbers = [3, 5, 7, 15];

5.4-Summary
C Example:
int a1[10]; // static global variable.
static int a2 = 5; // static global variable, initialized
void foo(){
static int a3[10]; // static local array variable
int a4[10]; // stack-dynamic variable
int *a5 = (int *)malloc(10*sizeof(int));
// a5 (pointer) is stack-dynamic
// *a5 is explicit heap-dynamic
...
free(a5);
}

5.5.6. Dynamic Scope


function big() {
var x: integer;
dynamic Static scoping
function sub1() {
scoping
... ?
(called
form big) ... x ... dynamic scoping
} (called form sub1)
function sub2 () {
var x: integer;
...
sub1 ;
}

Sub2();
sub1();
}
CS 315 Examples 4

5.8 Named Constants


Java and C++ allow dynamic binding of values to named constants.
Example in Java
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int a = kb.nextInt();
final int b = a * 2;
System.out.println(a+" "+b);
}
}

6. Data Types
6.3.3 String Length Options
• Limited dynamic length strings: (C and C++)
Following are equivalent in C
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};

6.4 Enumeration Types


• Example in C:
/* enumeration type in C */
main () {
enum day {mo, tu, we, th, fr, sa, su};
enum day today;
today = th;
if ((today == sa) || (today == su))
printf (“weekend\n”);
else printf (“weekday\n”);
}

6.5.3 Subscript Bindings and Array Categories


Heap-dynamic array: Similar to stack-dynamic array, but the size can change during the lifetime.

Advantage: the array can grow and shrink.


CS 315 Examples 5
Example:

ArrayList in Java, List in python, Arrays in perl (dynamic-array.pl)

Python
>>> mylist = [2, 1.6, (3+5j), 'c', "a word"]
>>> print mylist
[2, 1.6, (3+5j), 'c', 'a word']
>>> x = (1+2j) * mylist[2]
>>> x
(-7+11j)
6.6 Associative Arrays
Provided in Perl (called hash) and Java.

* Indexed by keys
* The size can grow and shrink dynamically.
#!/usr/local/bin/perl
%notlar = ("Ali" => 95, "Veli" => 80, "Selami" => 95);
To print an entry:
print "Veli’nin notu $notlar{Veli}\n";
To add a new entry:

$notlar{"Hulki"} = 75;
To delete an entry:
delete $notlar{"Veli"};
To change an entry:
$notlar{"Veli"} = 82;
To go through the array:
foreach $anahtar (keys %notlar) {
print "$anahtar $notlar{$anahtar}\n";
}
To empty the array:
%notlar = ();

6.8. Tuple Types


A tuple is a data type that is similar to a record, except that the elements are not named.

Ex: Python
>>> myTuple = (3, 5.8, 'apple')
>>> myTuple[1]
5.8
CS 315 Examples 6
>>> myTuple[1] = 6.7
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> myTuple = [3, 5.8, 'apple'] #Now, it is a list
>>> myTuple[1] = 6.7
>>> myTuple = (3, 5.8, 'apple') # Back to tuple
>>> yourTuple = (1, 'pear')
>>> print myTuple + yourTuple
(3, 5.8, 'apple', 1, 'pear')
>>> print yourTuple
(1, 'pear')
>>> del yourTuple
>>> print yourTuple
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'yourTuple' is not defined

List Types
Lists were first supported in Lisp and Scheme.

Ex: Python:
>>> myList = [1, 2.3, "three"]
>>> del myList[1]
>>> myList
[1, 'three']
>>> myList.insert(1,"orange")
>>> myList
[1, 'orange', 'three']
>>> myList.append("plum")
>>> myList
[1, 'orange', 'three', 'plum']

6.10. Union Types


A union type may store different type values at different times in the
same location.
Type checking must be dynamic.
Example in C:
#include <stdio.h>
#include <string.h>
CS 315 Examples 7
union Data {
int i;
float f;
char str[20];
};

int main() {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
Generates the following output:
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

Size of a variable of union type:


#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {
union Data data;
printf("Memory size occupied by data: %d\n", sizeof(data));
return 0;
}

Prints 20.

6.11.3.2. Lost heap-dynamic variables


C++ Example
void foo(){
int * x = new int;
}
foo(); // no way to reach the allocated integer: memory leakage
CS 315 Examples 8
C++ Example
int * x = new int;
x = new int; // no way to reach the first allocated integer: memory leakage

9. Subprograms
9.2.3 Parameters
Python Example / positional parameter passing
def sum(x, y, z):
return x + y + z
u = sum(a, b, c)

Python Example / positional with defaults


def sum(x, y, z=3):
return x + y + z
u = sum(a, b)
u = sum(a, b, c)

Python Example / keyword based:


def sum(x, y, z=3):
return x + y + z
u = sum(y=a, x=b)
u = sum(y=a, z=c, x=b)

Python Example / variable number of arguments:


def sum(x, y, *z):
s = x + y
for e in z:
s = s + e
return s
u = sum(a, b)
u = sum(a, b, c, 3, 5)

Python Example / variable number of arguments:


def sum(x, y, *z, **w):
s = x + y
for e in z:
s = s + e
for k,e in w.iteritems():
s = s + e
return s
u = sum(a, b)
u = sum(a, b, c, d, i=3, j=5)
CS 315 Examples 9
Python Example / unpacking:
def sum(x, y, z, t):
return x + y + z + t

v = [3, 5, 6, 8]
u = sum(*v) # same as sum(3, 5, 6, 8)

9.5.2 Parameter passing methods


The output of the program considering static scoping, sub-expression evaluation order of left-to-right,
and:

• parameter passing with pass-by-value-result


• parameter passing with pass-by-reference
• parameter passing with pass-by-value

int y;
int z;
int foo(int x) {
x = x + 5;
y = x;
x = x + 6;
return y;
}

int bar(int x){


y = foo(x) * x;
return x;
}

void main(){
y = 4;
z = bar(y);
print(y, z);
}
// Pass-by-value-result: 15 15
// Pass-by-reference: 225 225
// Pass-by-value: 36 4
9.5.2.5. Pass-by-name
Example in Scala
https://alvinalexander.com/source-code/scala/simple-scala-
call-name-example
(Scala is a type-safe JVM language that incorporates both object oriented and functional programming)
CS 315 Examples 10

9.6 Parameters That Are Subprograms


Python Example

def map(op, items):


res = []
for item in items:
res.append(op(item))
return res

def square(x):
return x*x

def triple(x):
return 3*x

print(map(square, [1, 2, 3])) # prints [1, 4, 9]


print(map(triple, [1, 2, 3])) # prints [3, 6, 9]

C++ Example

vector<int> map(int (*op)(int), vector<int> const & list){


vector<int> res;
for (int v: list){
int mappedValue = (*op)(v);
res.push_back(mappedValue);
}
return res;
}

int square(int x){


return x*x;
}

int triple(int x){


return 3*x;
}

vector<int> list = {1, 2, 3, 4};


vector<int> res = map(&square, list);
vector<int> res2 = map(&triple, list);

9.12. Closures
A JavaScript closure example:

http://dijkstra.cs.bilkent.edu.tr/~guvenir/closure.htm
CS 315 Examples 11
Python Example:
def make_adder(x):
def adder(y):
return x+y # x is captured from y.
return adder # make_adder returns inner function.

f = make_adder(3) # f is a function
print(f(5)) #prints 8
# 3 of the previous line is captured as x

C++ Example:

function<int(int)> make_adder(int x){


auto adder = [=] (int y) {return x+y; };
return adder;
}
auto adder = make_adder(3);
cout << adder(5);

9.13. Coroutines
Not exactly a full-coroutine implementation, but a similar feature in Python, “generators” example:
def genPairs(n):
for i in range(0, n):
for j in range(i+1, n):
yield (i, j)

for p in genPairs(5):
print(p)
CS 315 Examples 12

10. Implementing Subprograms


10.2 Implementing “Simple” Subprograms
Example in Fortran
INTEGER I,J
COMMON I
CALL X
GOTO 10
10 CONTINUE
END

SUBROUTINE X
INTEGER K, J
COMMON I
K=5
I=6
J=I+K
RETURN
END
The translator performs the following bindings for the main program:

I  d[COMMON, 0]
J  d[MAIN,1]
10  c[MAIN,3] CONTINUE statement
X  c[X,0] first statement of X
And the following bindings for the subroutine X:

I  d[COMMON, 0]
K  d[X, 1]
J  d[X, 2]

The linker then performs a further binding of addresses by combining the main program and the
subroutine X.

It produces the following bindings in the main program:

I  D[0]
J  D[2]
10  C[3]
X  C[5]
And the following bindings for X:

I  D[0]
K  D[4]
J  D[5]
CS 315 Examples 13
The contents of the memory will be as follows:

The contents of the Data memory during the execution:

You might also like