Mimir:Spring 2018 Lectures


 * Home
 * Textbook

= Week 1 - Introduction: categorizing programming languages = Content author Mike Jonas

Outline by Mike Jonas
 * How to Categorize a programming language
 * by paradigm: imperative, procedural, functional, logic, visual, oop
 * by its use: development vs utility
 * by implementation: interpreted, compiled, hybrid
 * by attribute: data typed, free format, indentation driven
 * by generation: 1st, 2nd, 3rd, 4th, 5th

Categorizing programming Languages
How do we discuss programming languages? What forms do we use to analyze the effectiveness of a language, be it a newly created one or one that has been around for a long time. We'll briefly hit upon five, some standard and some more practical. Note that here we will not delve into the specifics of each of the methods a programming language can be classified, that will be left to specific lectures following on subsequent weeks. We merely introduce the notions here.

Classifying by Paradigm
We generally look to paradigms (imperative, procedural, functional, logic, visual, oop, multi) when we discuss programming languages. These are tried and true classifications that a language fits into to. However, paradigm really only focus how the programmer is impacted when developing code and says little about how the language fits into the development cycle.

Classifying by Use
A less common way to look at programming languages is by its purported use, mainly because programmers have the freedom to apply any language to any solution. However, this does not always yield optimal results. Should one use a scripting language to develop a word processor? Some languages that gain public support end up being transformed and its purpose changes. Sometimes this results in a better, more powerful language and sometimes it becomes somewhat of a mess. Python is such a language that has become popular as now a development language.

Classifying by Implementation
Languages are generally interpreted or compiled (details to follow in week 2). There are some that use a hybrid approach (Java) compiling into an intermediate form and then using a virtual machine to run them. Is that virtual machine an interpreter or an emulator? That question requires further thought, however, classifying languages by implementation is a popular means to gauge effectiveness of use by programmers.

Classifying by Attributes
It could be argued that how a language is implemented is just an attribute, we separated it out (above) because it is a profound means to look at a language. In actuality, one could look at most of what has already been discussed as an attribute of the language. So this is a catch-all for smaller distinctions that may or may not deserve their own section. One such attribute is whether a language is "typed" or not (we mean data type here). Another is whether the language is free format (most) or uses indentation (Python) to determine block structure. Is the language case sensitive?

Classifying by Generation
A much less used (and somewhat older) means of talking about a programming language. First generation languages were the processor's code (aka machine code). Second generation languages mapped this machine code to more human readable form of an Assembly Language (a one-to-one mapping of mnemonics to instructions). Third generation languages gets us to where we are now with modern high-level languages (giving a one-to-many mapping from code to instructions). There are also fourth generation classifications focusing on systems such as DB's and fifth generation classifications designed to make the computer solve a given problem without the programmer (i.e. expert systems).

= Week 2 - Compilers, Interpreters and BNF grammars = Content authors (Group #1) Illya Kovarik and Sharmila Pankaja

Outline by Illya Kovarik
 * Tools used in Programming Languages
 * Compiler
 * what is it and how does it work (add picture)
 * pros and cons of compiler
 * Interpreter
 * what is it and how does it work (add picture)
 * pros and cons of an interpreter
 * How does an Assembler fit into this picture
 * explain what an assembler is
 * Grammars - what are their purpose
 * Backus Naur form - define and describe BNF and give examples
 * Context Free Grammars (CFG) - define and discuss
 * brief description explaining why CFG's are best for programming languages
 * Parsing - what is it and how does it relate to both grammars
 * where does it fit in with compilers and interpreter

Tools Used in Programming Languages
Various tools are used by software developers to create, debug, maintain or support their programs and applications. The most fundamental tools are some form of a text editor and then a compiler and/or an interpreter. These are the tools used to translate the text of the human language describing the desired flow of the program into the binary instructions to be run on the computer machine. Beyond those, a developer might use modeling tools on the front end and then debugging tools, profilers but also revision control and bug tracking tools on the back end. Since this course is about programming languages and their grammar, we focus on those relevant tools, such as the...

Compiler
A compiler is an essential and fundamental tool used by a programmer. It is a special type of computer program that translates the source code written in a familiar or preferred programming language into executable machine or object code to be run on a target device. An understanding of the compiler mechanism is important to a better understanding of the way languages are designed. A better understanding of the way languages are designed will, in turn, lead to a better mastery of their usage. Typically, the source is written in a high level language and the resulting output object is the machine binary. Computer programs can become very complex and to produce them in a productive way, instructions are abstracted into higher level languages in which the program is written. These are then compiled down to the binary machine code. Usually, the word 'compiler' refers to such translating programs written to process high-level language source down to lower level machine-executable binary code. The reverse type of compiler, machine code up to high-level language, would be called a 'decompiler'. A program which translates from one high level program to another high level, would be called a 'transpiler'. A program which compiles in its own language is called a 'bootstrap compiler'. A proper compiler program will include more than just the final code generation logic. It will generally consist of several program blocks which follow a flow of formatting, error checking, processing, code generation and optimization. These are not representative of any hardware structure, they are logical structures and also modular by nature so that they can be more easily updated and/or maintained. This is...

How It Works


A compiler can be viewed as a sequence of events. The source code file input, written in the familiar or preferred high-level programming language, follows these steps:


 * Source Code ---

The input to the compiler must be been written in a high level language which is intended to be compiled. Obviously then, the decision whether to use a compiled language and which one, needs to be made at a very early stage of the project. Examples of compiled languages include: C, C++, Visual Basic, etc. See Week 4 notes for an excellent survey of the various programming language paradigms.
 * Pre-processor ---

A pre-processor is a program that provides initial processing of an input to produce an output that is suitably formatted to be ready as the input to the next stage. As such, it is usually not a standalone program. It performs many of the basic error checking functions as well as the removal of commented sections of code. Pre-processing can also include the replacement of global variables with their actual value at every occurrence, processing of macros, file inclusion and certain language extensions which might have been implied in the programming language but now need to be explicitly stated in the compile.

This initial stage called the pre-processor will also include lexical analysis and tokenization. This is also called a lexer and is a scan routine in the pre-processor stage which reads the sequence of text characters of the program and generates a corresponding series of tokens based on the logical grouping. A token is a collection of characters which represent a single logical entity. Lexing is still a grouping mechanism and much of the complexity of semantic analysis is deferred to the next stage of parsing. An example of a lexer is lex, a program which generates lexical analyzers. Lex reads an input stream of characters which specify the lexical analyzer's functionality and it outputs source code implementing the desired lexer in the C programming language.


 * Parse ---

Parsing is the processing step of analyzing the string of input characters which constitute the program and builds a parse tree from the sequence of tokens produced by the lexical scanner of the previous stage. The parse tree is the grammar. Every expression is resolved into it's grammatical constituents. The result is an abstracted form of the original source.


 * Code-Generation ---

Meanwhile, the source has been pre-processed, tokenized, and checked for semantic correctness resulting in the parse tree, which is an internal abstracted version of the original source code. This abstracted intermediate representation of the source program is now ready to be converted into the object program output. The code generation stage is more specifically dependent on the target machine and operating system.


 * Optimizer ---

The optimizer is the process of rearranging and adapting the compiled program to produce a more efficient object program output. The optimization can modify the original source program by streamlining the logical flow. This usually does not depend on the target machine but is more of a type of "cleaning up" the code. It is something the programmer could have done but was perhaps limited by time constraints. The optimization can also modify the generated code with the intent to improve run efficiency on a particular target processor. This then does depend on the target machine and it is something that the programmer would usually not even attempt.


 * Assembler ---

The assembler stage creates object code by translating combinations of mnemonics, syntax for operations and addressing modes, into their binary machine-code equivalents.


 * Linker ---

Is the process of combining object files and libraries into a single output image. Static linking simply combines all library routines used in a program into the final executable file. Dynamic linking postpones the final linking until run time and then combines them interactively while the process is running.
 * EXE ---

The final output of a compiler is an executable program file, most typically with an .exe extension. This is the machine code output which can be loaded to the memory of a target computer device and run.

Pros and Cons
Programs written in high level language are either run using an interpreter or are translated into machine code by the compiler, assembler and linker chain. The choice which to use can be made easier by considering the pros and cons of each approach. Advantages to using a compiler include: Disadvantages to using a compiler include:
 * Self contained - Compiled programs are self contained modules which are ready to run. An executable is run, there is no ambiguity, and there is less setup or preparation requirements on the system and user.
 * Optimized to the hardware - Maximum hardware performance can be achieved. No compromises need to be made to allow more universal usage, code will also be more compact because of this.
 * Distribution - The code is packaged. The intellectual property can be more securely controlled when releasing a compiled version of a program. Compiled code is more readily put into production. The revision level of the code release is easily controlled.
 * Hardware specific - Once compiled, the code can only run on the specific platform it was intended to run on. Of course, that might also be perceived as a desirable feature, as it controls the usage.
 * Development Cycle - Compiling a very large program can take a long time (hours). During this time no changes can be made, the source code development is temporarily halted while waiting for the compile to complete.
 * Debugging - Finding bugs can be more challenging since the whole program has been compiled, there is no step-by-step translation to machine code, as in an interpreter. Small changes and little tweaks might not be made because of the overhead involved in running a compile.

Interpreter
An interpreter is, alongside with a compiler, an essential and fundamental tool used by a programmer. It is a special type of computer program that translates the source code written in a familiar or preferred programming language and runs it. The interpreter takes the source code and performs its behavior. It can be compared to a hand calculator which evaluates expressions as you enter them. An understanding of the interpreter mechanism is important to a better understanding of the way languages are designed. A better understanding of the way languages are designed will, in turn, lead to a better mastery of their usage.

The interpreter and the compiler are the two approaches by which programming languages are implemented. Yet, they are not mutually exclusive and an interpreter, at some level, must include translation to machine code to be able to run on the processor. Compilers can also include run-time interpretation. High level languages are not exclusively either interpreted or compiled. The line between compiler and interpreter can become blurry.

A proper interpreter program will include more than just the final run engine. It will generally consist of several program blocks which follow a flow of formatting, error checking, processing, and optimization. These are not representative of any hardware structure, they are logical structures and also modular by nature so that they can be more easily updated and/or maintained. This is...

How It Works:


The source code file input, written in the familiar or preferred high-level programming language, follows these steps in an interpreter:


 * Source Code ---

The input to the interpreter must be written in a high level language which is intended to be interpreted. Obviously then, the decision whether to use an interpreted language and which one, needs to be made at a very early stage of the project. Examples of interpreted languages include: JavaScript, Python, Perl, MATLAB, Excel (spreadsheet), and more. See Week 4 notes for an excellent survey of the various programming language paradigms.

Frequently, the input text editor and the interpreter will be combined into a single front-end application called an integrated development environment (IDE). Examples of these include Jupyter Notebook, MATLAB, Spyder (python), and others. The great advantage of these is the ability to cut and try algorithm development for rapid prototyping or modeling of a system and because of that, they are much favored in research and development environments.


 * Pre-processor ---

A pre-processor is a program that provides initial processing of an input to produce an output that is suitably formatted to be ready as the input to the next stage. As such, it is usually not a standalone program. It performs many of the basic error checking functions as well as the removal of commented sections of code. Pre-processing can also include the replacement of global variables with their actual value at every occurrence, processing of macros, file inclusion and certain language extensions which might have been implied in the programming language but now need to be explicitly stated in the compile.

This initial stage called the pre-processor will also include lexical analysis and tokenization. This is also called a lexer and is a scan routine in the pre-processor stage which reads the sequence of text characters of the program and generates a corresponding series of tokens based on the logical grouping. A token is a collection of characters which represent a single logical entity. Lexing is still a grouping mechanism and much of the complexity of semantic analysis is deferred to the next stage of parsing. An example of a lexer is lex, a program which generates lexical analyzers. Lex reads an input stream of characters which specify the lexical analyzer's functionality and it outputs source code implementing the desired lexer in the C programming language.


 * Parse ---

Parsing is the processing step of analyzing the string of input characters which constitute the program and builds a parse tree from the sequence of tokens produced by the lexical scanner of the previous stage. The parse tree is the grammar. Every expression is resolved into it's grammatical constituents. The result is an abstracted form of the original source.


 * Optimizer ---

The optimizer is the process of rearranging or adapting the parse tree to produce a more efficient program flow or faster code execution. The optimization can modify the original source program by streamlining the logical flow to a more optimized abstract syntax tree. This step can also include partial compiles of repeated steps or recursive statements.


 * Engine ---

There is no executable output file from an interpreter. An interpreter engine performs the actions described by the high level program.

Pros and Cons
Programs written in high level language are either run using an interpreter or are translated into machine code by the compiler, assembler and linker chain. The choice which to use can be made easier by considering the pros and cons of each approach. Advantages to using an interpreter include:

Some disadvantages to using an interpreter:
 * Development cycle - During software development frequent changes are made to the source code. Changes to a program which is then executed by an interpreter can be run immediately, by partial blocks of code, or even statement by statement. There is no waiting for the whole program to compile before being able to see the result. This can be a great advantage during algorithm development when trying things out and tinkering is more important than run time efficiency, which can come later.
 * Portable - The source code can run across platforms, it is not specific to one machine.
 * Transparency - The source itself is run and that can make it more apparent what is going on, as opposed to a compiled program, where the user would have no idea of what is going on behind the scenes. Breakpoints can be set and the source code can be interpreted block by block. This is why interpreted programs are favored in scientific research.
 * Distribution - The source code itself is distributed and it must be interpreted every time it is run. Since it is the source and is easily read or copied, it is hard to control intellectual property rights or to enforce a copyright.
 * Efficiency - An interpreted program will run slower than a compiled program because it has to do the whole job of translation to machine code on the fly.
 * Regression - An interpreter can itself be interpreted which can itself be interpreted but eventually directly executed (compiled) machine code is needed to run the core machine instructions on the processor. However high-level the source code may be, the translation process will always need to arrive at that lowest machine code level because that is the way the processor works.

Assembler
Assembly is a low-level programming language to write instructions to a programmable device. There is typically a one-to-one correspondence between the assembly language and the processor's machine code instruction set. The assembly language consists of mnemonics which are intended to aid humans in the task of programming. Every assembly language is specific to every machine architecture and is therefore not portable across architecture platforms. High level programming languages differ in this regard, in that they are usually portable across processor architectures but they then require translation back down to the machine code via either a compiler or interpreter. The assembler itself is a utility program which translates the assembly code into executable machine code. The running of this utility program is called 'assembly'. Assembly programs are often provided by the manufacturer of the processor. Assembly is also one of the final steps in the compiler, see above.

How It Works
Assembly programs are written using the defined mnemonic processor instructions. This instruction set can be found in the processor datasheet. Instruction, data definitions and assembly directives are included in the overall assembly program. The assembly instructions consist of the mnemonic code for the instruction followed by data, arguments or other parameters. When the code is assembled, the instructions are translated into the machine code of the target device which can then be loaded into the memory and executed. Assembly resembles a compiler overall, in that an executable file is the result; there is an output which can be run on a target device.

Historically, assemblers were used to extract the highest possible performance from a processor, optimizing efficiency, cost, etc. With the commodification of hardware, this is no longer strictly true and sometimes the longer development time will outweigh the potential performance advantages. Raw processor speed is usually fast enough to make execution speed a non-issue. Compilers have also improved to the point where the difference in performance is negligible. Yet, certain situations still lend themselves to the use of assembly language, such as:
 * Boot loaders and device drivers. Programs which interact directly with hardware
 * Stand-alone executable of compact size without run-time libraries in many embedded applications, such as home appliances.
 * Reverse-engineering (hacking).
 * Mass-market games and toys, where absolute lowest cost is critical.
 * Programs where precise timing is needed, such as inner loops in real-time processing algorithms.
 * Programs where absolute control is required and nothing can be taken for granted, such as military applications.

Grammars
Grammars are metalanguages. A formal grammar is a set of rules for rewriting strings from a start symbol from which the rewriting originates. Grammars are used to make statements about statements in other languages and to specify the rules of syntax. The structure formulated by a grammar leads to a systematic way of processing the expressions written in a programming language. In that respect, the grammar can also be seen as a language generator.

From a historical perspective, the formal study of grammar goes back to ancient times. The word 'grammar' is derived from the same ancient Greek language root as 'graph' and was originally 'the art of letters'. The study of computer language is closely akin with the study of natural languages and several famous researchers of computer languages have, in fact, been linguists.

But before proceeding, for the sake of accuracy, a few definitions of terms in common use:
 * Syntax - Is the set of rules, principles, and processes that govern the structure of statements in a given language. This usually also includes the ordering of words or commands.
 * Semantics - Is the relationship between commands and phrases and what they stand for, their meaning or significance. Semantics differs from syntax, which merely concerns with the correct structure and combinations but without reference to any meaning. Meaningless or nonsensical statements can be syntactically correct.
 * Usage - A less formal definition, this refers to the common practice of how a language is deployed, what typical expressions, typical constructs, etc. This is much broader in natural languages, where idiomatic expressions might be part of the usage.

Backus Naur Form (BNF)
Is a formal notation technique used for the description of context-free grammars. It is used to define the syntax of computer languages but can also be used to describe document formats, communication protocols and wherever exact descriptions of languages are needed.

The particular type of grammar we use is called a Context-Free Grammar , because each expression has the same form in any context. This is further explained below. There are four components which constitute BNF format of language production rules:

TERMINAL SYMBOL • These are the symbols or words that make up the strings of the language. They could be letters (A, B, C, . . .) or words (a, aardvark, abacus,)or these terminals can be any symbols which are appropriate to the domain.

NON TERMINAL SYMBOLS • A set of nonterminal symbols that categorize subphases of the language. For example, the nonterminal symbol Noun Phrase in English denotes an infinite set of strings including “you” and “the big slobbery dog.”

START SYMBOL • A start symbol, which is the nonterminal symbol that denotes the complete set of strings of the language. In English, this is Sentence; for arithmetic, it might be Expr , and for programming languages it is Program.

REWRITE RULES • A set of rewrite rules of the form LHS → RHS, where LHS is a nonterminal symbol and RHS is a sequence of zero or more symbols. These can be either terminal or nonterminal symbols, or the symbol ǫ, which is used to denote the empty string. A BNF specification is a set of derivation rules written as follows:

BNF Example: A simple conditional expression:

 ::= if  ::= == ::= <  ::= >  ::=

BNF Example: A simple arithmetic expression

 ::=    |  |   ::=  |    ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9  ::= + | − | ÷ | ×

Context Free Grammars (CFG)
Is a specific type of formal grammar where a set of production rules describe all possible string combinations in a language. The production rules are systematic replacements which do not depend on the context. The term might seem misleading, implying that the grammar is free of or has no context. It means that the language is context invariant, or simply not dependent on any context in particular. Any given contextual situation does not change the CFG rules to be applied.

Why CFG's Are Best For Programming Languages
The memory of a programming language is limited. The grammar cannot remember the presence of a construct over an arbitrarily long input. Since these grammars are not dependent on a context, they can be mapped unambiguously to exact meaning by using the production rules of the grammar. In other words, the task can be done by machine and this process is an element of the compiler we have just discussed. It means all of the language's production rules have a single non-terminal on its left hand side.

Parsing
Parsing is the process of analyzing a string or a text into logical syntactic components. This is done in order to test conformity to the formal grammar in which the string or text was written. Another name for this is 'clause analysis'. A parser is itself a computer program that takes the input text of the computer program to parse and builds from it a parse tree, which is an abstract syntax tree. This gives a structural representation of the input text (the program being parsed), and checks for correct syntax in the process.

Relation to Compilers and Interpreter
Parsing, as we have seen above, is preceded by a lexical analyzer and is one of the key processing steps in both compilers and interpreters. The use of the parser varies by the type of input. In the case of data languages, a parser is often found as the file reading facility of a program. In the case of programming languages, a parser is a component of a compiler or interpreter, that parses the source code written in a computer programming language to create some form of formal internal representation.

= Week 3 - An Overview of Perl (Cancelled due to snow) = Content authors Mike Jonas

Outline by Mike Jonas
 * Overview of Perl - give a one paragraph introduction about the history of the language
 * A couple of paragraphs discussing its basic structure (i.e. it's a statement based/imperative language)
 * add an example to highlight that
 * Types in Perl - one paragraph discussion of three types: scalar, array, hash
 * Scalar - add an example to show syntax
 * Array - add an example to show syntax
 * Hash - add an example to show syntax
 * Print statement - one paragraph discussion of what it's used for
 * add example to show syntax on how to construct printed strings via concatenation operator "."
 * Conditionals - one paragraph discussion of the two types if & if/else
 * add example to show syntax of if
 * add example to show syntax of if/else
 * Loops - one paragraph discussion of both while and for loops
 * add example to show syntax of while loop
 * add example to show syntax of for loop
 * File I/O - one paragraph discussion of file i/o
 * add example to show syntax of how to read from a file (use a while loop like we did in class)
 * Subroutines - one paragraph discussion of subroutines (i.e. what they are)
 * add example to show syntax of a subroutine, specifically how to pass parameters

Overview of Perl
Notes by Freddie Lochner

History
Perl was created by Larry Wall in 1987 for use as a text-processing utility (as opposed to a word processing program) for Unix-like operating systems. Prior to its creation, basic text manipulation was through the use of a collection of lighter, specialized utilities such as AWK, grep and sed. These could be piped together on the command line or saved into a bash script for later reuse. Either way, the commands were full of switches, pipes and redirects which could make them difficult to interpret, even by the coder. Of course, text processing could also be accomplished with heavier languages like C, but that process is a bit complex for the purpose of writing a quick script. Over the years Perl evolved, and by 1992 with the release of Perl 4, had graduated from a simple, convenient tool to a viable general purpose programming language. By 1994 with the release of Perl 5, it had overcome the limitations and confusion that plagued the prior version, and was then considered a mature, and subsequently widely accepted programming language. Perl is still maintained and is currently Perl 6 on release 5.24.1 (14 Jan 2017). Source: Picking Up Perl, Edition 0.12, A Freely Redistributable Perl Tutorial Book

Basic Structure
As an imperative, statement-based language, Perl's basic structure is the performance of one action followed by another, along the way manipulating memory registers via assignments and calculations.

For example, the following code manipulates the memory registers allocated for the variables $a and $b.

$a = 2;         # the value in a's memory register is 2. $b = 4;         # the value in b's memory register is 4. $a = $b + 7;    # the value in a's memory register is now 11. # the value in b's memory register is still 4.

Types in Perl
Scalars

Perl is considered a loosely-typed language, meaning a variable can be any type of scalar (single value) such as an integer, float or string. They are prepended with $ as in the previous example.

$a = 4; $b = "hello"; $c = 12.2;

A variable's type can also be changed at will, from a string to an integer for example. Conversely, in strongly-typed languages such as C, variables must be declared a specific type and cannot be changed to another later. An example in Perl:

$a = 5;         # a is an integer $a = "hello";   # a is now a string

Arrays

Variables can also be an array (list) of scalars, denoted by @ which can be comprised of mixed scalars:

@e = (4, 5, 1); @f = ("apple", "pear", "banana"); @g = ("orange", 5, 7.2);

Accessing members of an array is a simple affair. Arrays are zero-indexed, meaning the first member is '0'. Notice that when accessing members, the value is a scalar.

Using the previous example,

$j = $e[1];     # the value in j's memory location is 5. $k = $f[2];     # the value in k's memory location is "banana". $l = $g[0];     # the value in l's memory location is "orange".

Hashes

One of Perl's most efficient and powerful operations deals with the management of hashes, known in other languages as associative arrays, dictionaries or maps. A hash is an un-ordered list of key-value pairs. The keys are always strings and their values are scalars.

Initializing scalars can be as simple as declaring a variable as a hash, or like any other variable, it can be loaded with key-value pairs. There are three ways to initialize hashes:

%fruits = ("apple", "red", "banana", "yellow", "orange", "orange");

The example above is perfectly legal, but looks more like a list than a set of key-value pairs.

The following example uses the "fat comma" and is much more clear:

%fruits = ("apple" => "red", "banana" => "yellow", "orange" => "orange");

Remember that the key is always a string, so in Perl the quotes around the key can be left off, presenting the clearest and cleanest method of initializing a hash:

%fruits = (apple => "red", banana => "yellow", orange => "orange");

Adding a key-value pair to a hash looks similar to adding an item to an array, but hashes use curly braces. Notice the scalar ($) assignment:

$fruits{grape} = "purple";

Accessing members of a hash is similar to a list as well. Using the previous example:

print ($fruits{banana});

will output the following at runtime:

yellow

Print Statements
Perl code can contain print statements which present text on the screen during runtime. Perl does not require the use of parentheses to use most built-in functions, but their use makes the code more readable, and is encouraged. Escaping certain characters (prepending a '\'), such as \n or \t will insert a newline or tab, respectively. Escaping variable type symbols such as \$ or \@ will print the character $ or @ rather than interpreting the symbol and dereferencing the variable.

Using the values from the previous example, this code: print ("The value of the second member of the array \@f is: $f[1].\n"); will output the following during runtime: The value of the second member of the array @f is: pear. print converts its arguments to strings, which can be concatenated with a dot (.), which is of particular convenience when using the return value of an embedded function or operation. Notice the addition operation must be enclosed in parentheses.

For example: $a = 4; $b = 8;

print("hello\t".($a + $b)." there.\n"); will output the following during runtime: hello  12 there.

Conditionals
Conditional code blocks are used to perform a certain action based on the true or false value of a comparison of two like-types.

Strings and numbers are compared similarly, but use different operators.

If statements

In the following example the flow of the program skips the code block, denoted by, and wrapped with, curly braces: '{' and '}' because the conditional is false. Line-terminating semi-colons are not required after a code block. $a = "banana"; $b = 2;

if ($a eq "peach") {  $b = 8; }

print ("The value of \$b is: $b\n"); Because $a did not equal 3 during runtime, the value of $b did not change, so the output will be: The value of $b is: 2

If statement with Else and Else-If

Conditional code blocks can be made more flexible with the use of else, and even more so with the use of one or more elsif conditionals, as below: $a = 4; $b = "two";

if ($a == 3) {  $b = "three"; } elsif ($a == 5) {  $b = "five"; } elsif ($a == 6) {  $b = "six"; } else {  $b = $a; }

print ("The value of \$b is: $b.\n"); Since the if and neither elsif was true, the else block acts as a catch-all and presents the following output during runtime: The value of $b is: 4.

Loops
In programming, a loop is way of performing an action one or more times. There are two kinds of loops, for-loops and while-loops. Choosing the right one depends on whether the number of times is known or unknown during the coding of the loop.

For loop

In the case of a for-loop, the action is performed a concrete number of times. The loop is initialized, tested for a certain value, then incremented. The loop continues until the test condition is false. Below is a diagram of how a for-loop operates:

for ( $a = 10; $a < 15; $a = $a + 1 ) {   print ("The value of \$a is: $a\n"); } Because the condition $a < 15 is true while $a is incremented from 10 to 14, the following will be presented at runtime: 10 11 12 13 14

While loop

A while-loop is similar to a for-loop, but the number of iterations depends on the unknown value (during programming) of some other variable. In the following example, previous code has left the value of $a at '-1' and $b at '7'. $a = 0; $b = 0;

(code)

while ( $a <= $b ) {   print ("The value of \$a is: $a\n"); $a = $a + 2; } The condition ( $a <= $b ) is true until $a is incremented to 7, so the following will be presented at runtime: -1 1 3 5 7

File I/O
Reading from a file in Perl is a three step process: In the following example, the file to be read in contains three lines of text, each ending with a newline character.
 * The file is opened and assigned a handle (an object that tells Perl how to interact with it).
 * A loop is used to read the lines one-by-one.
 * The file handle is closed.

Contents of file.txt: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Code to read in the contents of the file and present it to the screen: $a = 1;                         # Initialize $a which will be the line counter for output. (The use of a line counter is unnecessary                                #    when reading in a file - It is only used here to clarify the output)

open (DATA, "<", "file.txt");   # DATA is the filehandle, and the "<" tells Perl to open the file in read-only mode.

while (

When the assignment statement is executed the variable `count` is updated with a new value. Assignment statement can be executed many times with the same variable and each time the variable will be updated with a new value. The variable is mutable. This proves the state mutation nature of the assignment statement.

Object-oriented programming is centered around class definition, object instantiation, state mutation and method invocation operations. All operations are expressed in object-oriented languages using statements. An object-oriented program consists of a sequence of statements that are executed in order. Statements mutate the program state during the program execution. The sequence of state mutating statements leads to the final result of the program.

The essence of statement execution is program state mutation. Statement execution produces side effects. Side effect is program state mutation as a consequence of statement execution. The execution of a statement changes the program environment. The result of statement execution depends on program environment. The same statement can produce different side effects depending on the environment it is executed in.

Flow Control
Control flow manipulates execution of the code. This is typically done by conditionals or loops. In imperative programming, control flow statement regulates the order in which individual statements, instructions or function calls are executed. Control flow is also explicit in imperative program, in contrast of declarative program which is implicit. Within an imperative program, a control flow statement is a statement the execution of which results in a choice being made as to which of two or more paths to follow.

Statements connected by simple but powerful control structures have a single entry and exit point. Collectively, these structures can handle any situation. The proper of control flow use leads naturally to a well-structured program and avoid spaghetti logic. Spaghetti code has a complex and tangled control structure, especially using many GOTO statements, exceptions, threads, and "unstructured" branching constructs. In a well structured program, each statement jumps from one to another, but this jumping is formal and more easily predictable, because for loops and functions provide flow control whereas the GOTO statement encourages arbitrary flow control.



Conditional Statement
Conditional statement checks the value of a variable from the program environment and executes the assignment statement. The assignment statement mutates program state by updating the variable in place. There is no return value from a conditional statement, only program state mutation.

In imperative programming languages, conditional statement is usually used, whereas in functional programming, the terms conditional expression or conditional construct are used due to different meanings. Conditional statements perform different computations or actions depending on whether a Boolean condition evaluates to true or false.

IF
The simplest form of IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF (not ENDIF), as follows:

IF condition THEN sequence_of_statements END IF;

The sequence of statements above is executed only if the condition is true. If the condition is false or null, the IF statement does nothing. In either case, control passes to the next statement. An example here: IF x > y THEN high := x; END IF;

IF-ELSE
The second form of IF statement adds the keyword ELSE followed by an alternative sequence of statements, as follows:

IF condition THEN sequence_of_statements1 ELSE sequence_of_statements2 END IF;

The sequence of statements in the ELSE clause is executed only if the condition is false or null. Thus, the ELSE clause ensures that a sequence of statements is executed.



IF-THEN-ELSEIF
Sometimes you want to select an action from several mutually exclusive alternatives. In many programming languages, the third form of IF statement uses the keyword ELSIF (ELSE IF) to introduce additional conditions, as follows:

IF condition1 THEN sequence_of_statements1 ELSIF condition2 THEN sequence_of_statements2 ELSE sequence_of_statements3 END IF;

If the first condition is false or null, the ELSIF clause tests another condition. An IF statement can have any number of ELSIF clauses; the final ELSE clause is optional. Conditions are evaluated from top to bottom. If any condition is true, its associated sequence of statements is executed and control passes to the next statement. If all conditions are false or null, the sequence in the ELSE clause is executed.

SWITCH
Switch statements in a programming language compare a given value with specified constants and take action according to the first constant to match. There is usually a provision for a default action to be taken if no match succeeds, but it’s optional. SWITCH uses CASE and DEFAULT within its structure to perform a conditional task. The SWITCH statement is preferred in cases where there is a lengthy list that needs to be compared with the variable.

SWITCH (conditional expression) { case 1: statement 1; case 2: statement 2; case 3: statement 3; default: statement 4; }



Loop Statement
Looping statement executes repeatedly a set of statements mutating the looping variable and the program state. Loop statements execute repeatedly several number of times. There is no return value from looping statement only program state mutation. There are a few side effects when working with loop statements. For Loop usually specifies a number of times it is iterated whereas While Loop is an infinite loop until a condition is met. Both options offer some flexibility as to how they are executed.

FOR LOOP
For loop is a statement which allows code to be repeatedly executed. For loop contains 3 parts Initialization, Condition and Increment or Decrements.


 * Initialization: This step is executed first and once when we are entering into the loop first time. This allows us to declare and initialize any loop control variables.
 * Condition: This is the next step after initialization step, if it is true, the body of the loop is executed, if it is false then the body of the loop does not execute and flow of control goes outside of the for loop.
 * Increment or Decrements: Increment or Decrement step is executed, after completion of Initialization and Condition steps where loop body code is executed. This statement allows to update any loop control variables.

for (initialization; condition; increment) { statement(s); }



An example of for loop:

Looping statement mutates the state of the count variable and executes arr mutation statement multiple times. If the count variable is modified with assignment statement within the body of looping statement, the side effect of the same looping statement is different:

WHILE LOOP
The WHILE-LOOP statement associates a condition with a sequence of statements enclosed by the keywords LOOP and END LOOP, as follows:

WHILE condition LOOP sequence_of_statements END LOOP;

Before each iteration of the loop, the condition is evaluated. If the condition is true, the sequence of statements is executed, then control resumes at the top of the loop. If the condition is false or null, the loop is bypassed and control passes to the next statement.



DO WHILE LOOP
Do while loop is a control flow statement that executes a block of code at least once, or not, depending on Boolean condition at the end of the block.

The do while construct consists of statements and a condition. First, the statement code within the block is executed, and then the condition is evaluated. If the condition is true, the code within the block is executed again. This repeats until the condition becomes false. Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop. Do-while loop is also referred to as an exit-condition loop.

do { do_work; } while (condition);

is equivalent as:

do_work; while (condition) { do_work; }

It is possible for the condition to always evaluate to true, creating an infinite loop. When such a loop is created intentionally, there is usually another control structure (like a break statement) that allows termination of the loop.

Break statement provides an exit out of the loop: while (true) { do_work; if (!condition) break; }



The above diagram shows the flow control for the Python function cube_first_two(input_list). Considering the test function cube_first_two([2, 4, 6, 8]), the following flow control takes place:
 * 1) The Python interpreter executes line 1, which tells the engine that a function named cube_first_two is being defined with a single parameter, input_list.
 * 2) The Python interpreter skips over the docstring located on lines 2 through 8.
 * 3) The Python interpreter executes line 9 (Sequential Flow 1), creating an empty list named new_list.
 * 4) The Python interpreter executes line 10 (Sequential Flow 2), initializing item_count as an integer with the value of 0.
 * 5) The Python interpreter executes line 11 <font color="#0000FF">(Sequential Flow 3), which tells it to start a loop until the condition ‘item_count is less than the length of input_list’ is True.
 * 6) The Python interpreter executes line 12 <font color="#0000FF">(Sequential Flow 4), setting item_count to 1.
 * 7) The Python interpreter executes line 13 <font color="#0000FF">(Sequential Flow 5), which tells it to check the condition ‘item_count is less than or equal to 2’ – which it is (1).
 * 8) The Python interpreter executes line 14 <font color="#FF0000">(Conditional Flow 1 ), initializing a variable named new_value to the value associated with the expression of the (item_count minus 1)th item in the input_list raised to the power of three (cubed), which sets new_value to 8.
 * 9) The Python interpreter executes line 15 <font color="#0000FF">(Sequential Flow 6), which appends the new_value of 8 to new_list.
 * 10) The Python interpreter checks line 16 <font color="#FF0000">(Conditional Flow 2), and finds that the else statement doesn’t apply in this iteration.
 * 11) The Python interpreter skips line 17, and goes to line 18 <font color="#FF0000">(Conditional Flow 3), which is blank, which tells the interpreter to go back to the while loop to check the condition again.
 * 12) The Python interpreter executes line 11 <font color="#BF9D26">(Loop Flow 1), which tells it to continue the loop because the condition ‘item_count (1) is still less than the length of input_list’ (4).
 * 13) The Python interpreter executes line 12 <font color="#0000FF">(Sequential Flow 4), setting item_count to 2.
 * 14) The Python interpreter executes line 13 <font color="#0000FF">(Sequential Flow 5), which tells it to check the condition ‘item_count is less than or equal to 2’ – which it is (2).
 * 15) The Python interpreter executes line 14 <font color="#FF0000">(Conditional Flow 1), updating the variable named new_value to the value associated with the expression of the (item_count minus 1)th item in the input_list raised to the power of three (cubed), which sets new_value to 54.
 * 16) The Python interpreter executes line 15 <font color="#0000FF">(Sequential Flow 6), which appends the new_value of 54 to new_list.
 * 17) The Python interpreter checks line 16 <font color="#FF0000">(Conditional Flow 2), and finds that the else statement doesn’t apply in this iteration.
 * 18) The Python interpreter skips line 17, and goes to line 18 <font color="#FF0000">(Conditional Flow 3), which is blank, which tells the interpreter to go back to the while loop to check the condition again.
 * 19) The Python interpreter executes line 11 <font color="#BF9D26">(Loop Flow 1), which tells it to continue the loop because the condition ‘item_count (2) is still less than the length of input_list’ (4).
 * 20) The Python interpreter executes line 12 <font color="#0000FF">(Sequential Flow 4), setting item_count to 3.
 * 21) The Python interpreter executes line 13 <font color="#0000FF">(Sequential Flow 5), which tells it to check the condition ‘item_count is less than or equal to 2’ – which it is not (3).
 * 22) The Python interpreter advances to the else statement on line 16 <font color="#FF0000">(Conditional Flow 4), and then executes line 17, which appends the value of the expression of the (item_count minus 1)th item (6) to new_list <font color="#0000FF">(Sequential Flow 7).
 * 23) The Python interpreter advances to line 18 <font color="#0000FF">(Sequential Flow 8), which is blank, which tells the interpreter to go back to the while loop to check the condition again.
 * 24) The Python interpreter executes line 11 <font color="#BF9D26">(Loop Flow 1), which tells it to continue the loop because the condition ‘item_count (3) is still less than the length of input_list’ (4).
 * 25) The Python interpreter executes line 12 <font color="#0000FF">(Sequential Flow 4), setting item_count to 4.
 * 26) The Python interpreter executes line 13 <font color="#0000FF">(Sequential Flow 5), which tells it to check the condition ‘item_count is less than or equal to 2’ – which it is not (4).
 * 27) The Python interpreter advances to the else statement on line 16 <font color="#FF0000">(Conditional Flow 4), and then executes line 17, which appends the value of the expression of the (item_count minus 1)th item (8) to new_list <font color="#0000FF">(Sequential Flow 7).
 * 28) The Python interpreter advances to line 18 <font color="#0000FF">(Sequential Flow 8), which is blank, which tells the interpreter to go back to the while loop to check the condition again.
 * 29) The Python interpreter executes line 11 <font color="#BF9D26">(Loop Flow 1), which tells it to end the loop because the condition ‘item_count (4) is not less than the length of input_list’ (4).
 * 30) The Python interpreter advances to line 19 <font color="#BF9D26">(Loop Flow 3) and executes the return statement to return the value of a list with the value of [8, 64, 6, 8]. The program has now completed all steps.

Expressions
Expression is a combination of one or more values, constants, variables, operators, and functions that the programming language interprets and computes to return another value. Variables and operators, are basic building blocks of programs. Certain expressions can be made into statements which are complete units of execution. Expressions perform the work of a program.

Expressions are used to compute and to assign values to variables and to help control the execution flow of a program. The job of an expression is to perform the computation indicated by the elements of the expression and to return a value that is the result of the computation. In languages that mix imperative and functional programming, such as Lisp, the distinction between expressions and statements is not made. In functional programming, there are no statements; everything is an expression. The distinction is usually observed in wording: a statement is executed, while an expression is evaluated.

In Python, an expression is a combination of values, variables, and operators. If you type an expression on the command line, the interpreter evaluates it and displays the result: >>> 1 + 1 2

The evaluation of an expression produces a value, which is why expressions can appear on the right hand side of assignment statements. A value all by itself is a simple expression, and so is a variable. >>> 17 17 >>> x 2

Boolean Expression
Boolean expression is a logical statement that is either TRUE or FALSE. Boolean expressions can compare data of any type as long as both parts of the expression have the same basic data type. You can test data to see if it is equal to, greater than, or less than other data.

A Boolean expression can consist of Boolean data, such as:
 * BOOLEAN values (TRUE and FALSE)
 * BOOLEAN variables or formulas
 * Functions that yield BOOLEAN results
 * BOOLEAN values calculated by comparison operators

Numeric Expression
Numerical expression is an arithmetic expression that results in a value. There are two kinds of numeric values, integers (whole numbers), and floating point numbers (numbers containing a decimal point). Operators act on operands to yield a result. Basic arithmetic operations are addition, subtraction, multiplication and division. There are also more advanced operations, such as manipulations of percentages, square roots, exponents, and logarithmic functions.

Arithmetic expression contains operators and operands, such as: 1 + 5 8 * 7 7.3 / 2 80 % 25

Operators
Operators are special symbols that represent computations like addition and multiplication. The values the operator uses are called operands.

The basic arithmetic operators for programming are:



Commonly used arithmetic operators are +, -, *, / and %. PEMDAS is an acronym for the words Parenthesis, Exponents, Multiplication, Division, Addition, Subtraction. Given two or more operations in a single expression, the order of the letters in PEMDAS tells you what to calculate first, second, third and so on, until the calculation is complete. If there are grouping symbols in the expression, PEMDAS tells you to calculate within the grouping symbols first. However, other operators such as modulus is often left out. * and % have equal precedence, so left takes precedence over right, as with multiply and divide.

Order of Operations
Without PEMDAS, there are no guidelines for order of operations. As an example, to calculate 2 * 5 + 7, I could multiply first, and then add to get 17. I also have the option to add first, then multiply and get 24. Which answer is correct? Using PEMDAS as the rules of operation – the correct answer is 17, because the order of the letters in PEMDAS tell me that multiplication should be performed before addition.

Here's an explanation of the rules given in PEMDAS:
 * Parentheses – complete any calculations in grouping symbols first.
 * Exponents – Ignore any other operation, and take any numbers with exponents to their respective powers.
 * Multiplication and Division operations actually have the same priority. Complete only those two operations in the order they occur from left to right.
 * Addition and Subtraction operations also have the same priority. You look for these last two operations from left to right and complete them in that order.

Some programming languages use precedence that conform to arithmetic used in mathematics, others such as such as APL, Smalltalk or LISP, have no operator precedence rules.

The relative precedence levels of operators found in many C-style (C++, Perl and PHP) languages are as follows:

Other methods: Immediate Execution
Calculator input methods are different than PEMDAS rule. Calculators have two category types - immediate execution and expression formula calculations. On a formula calculator, someone types in an expression, and the value is evaluated. On an immediate-execution calculator, the user presses a key for each operation, by pressing keys to calculate all the intermediate results, before the final value is shown. In fact, the order of operations is not taking into account on immediate execution. Scientific calculators have buttons for brackets and can take order of operation into account. Operations like √ or x2 the number is entered first, then the operator. Simple four-function calculators, such as those included with most operating systems, usually use this input method.

= Week 5 (& 4) - An overview Lisp = Content authors (Group #3/4) Raghava Adusumilli and Arjun Padaliya

Outline by Raghava Adusumilli
 * Lisp - explain the paradigm and what it implies for Lisp.
 * A little history, background and application of Lisp (i.e. Artificial Intelligence).
 * Give a brief overview of the language with Lisp example of each
 * Recursion in Lisp - discuss and give a coding example (i.e. fibonacci or factorial)
 * Basic components - discuss
 * atoms, lists and s-expressions
 * Some common functions
 * Assignment: set (remind readers to quote arguments with ' to prevent evaluation)
 * Math functions: +, -, *, /
 * List functions: list, cons, append, car, cdr
 * Defining functions: defun
 * Conditional functions: cond, null
 * Examples programs in Lisp
 * factorial function
 * a reverse function
 * a function that doubles each element in lisp

LISP
LISP, which stands for LISt Processor, is a functional programming language. Functional programming is a paradigm in which the all the functionality of a program are written as functions and each of these functions does one specific task/computation, always returns a value and causes no side effects. No side effect means the function should not make changes to a program which could potentially affect the flow of the program. One such example could be variable mutations which could alter the flow through control structures.

LISP with functional paradigm causes every statement in the program to be a function, including control structure statements and also allows the user to use any statement as an expression inside any other statement. For example, a COND statement, which is a control structure statement similar to if...else... in other languages can be used as the conditional expression of COND statement, whereas, this is not possible in any other programming paradigms. For example, if...else... cannot be used as the conditional expression of another if...else...

History, background and application
LISP is the second high-level programming language invented one year after FORTRAN. John McCarthy first invented LISP in 1958 and then published a paper in Communications of the ACM, titled "Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I" in 1960. McCarthy created LISP originally with bracketed M-expressions, i.e., [CAR[CDR[1,2]]], which would be then translated to S-expressionsBold text', i.e., (CAR (CDR (1 2))) by the machine. But, developers preferred the S-expression notation and abandoned the M-expression notation. Steve Russel, after reading McCarthy's paper in Communications of the ACM in 1960, first implemented LISP on an IBM 704 computer.

LISP was closely connected with the artificial intelligence research community, especially on PDP-10 (The PDP-10 is a mainframe computer family manufactured by Digital Equipment Corporation (DEC) from 1966) systems. LISP was also used to implement Micro Planner, which was used in the famous AI system SHRDLU. In the 1970s, as AI research spawned commercial offshoots, the performance of existing Lisp systems became a growing issue. Garbage collection routines, developed by MIT graduate student Daniel Edwards, made it practical to run Lisp on general-purpose computing systems, but efficiency was still a problem. This led to the creation of Lisp machines: dedicated hardware for running Lisp environments and programs.

Atoms
code examples
 * An atom is a word or a number or the pair of parentheses "" which we will call "NIL".
 * An atom can be any number the computer understands. This is called a numeric atom. These are integers like: 145, -15, 0, etc., or floating point numbers [ones with fractional parts] like: 1.4, -56.3, etc.
 * A non-numeric atom can be any name made up of letters and/or numbers. There is no limit on the length of this.
 * The form of NIL "" can be an atom.

Lists
code examples
 * Lists are the most important and the primary composite data structure in traditional LISP. LISP provides other data structures like, vector, hash table, classes or structures.
 * Lists are single linked lists. In LISP, lists are constructed as a chain of a simple record structure named cons linked together.

Cons
code examples
 * A cons is a record structure containing two components called the car and the cdr. Cons cells or cons are objects are pairs of values that are created using the function cons.
 * The cons function takes two arguments and returns a new cons cell containing the two values. These values can be references to any kind of object. If the second value is not nil, or another cons cell, then the values are printed as a dotted pair enclosed by parentheses.
 * The two values in a cons cell are called the car and the cdr. The car function is used to access the first value and the cdr function is used to access the second value.

S-expression
In computing, s-expressions (for "symbolic expression") are a notation for nested list (tree-structured) data, invented for and popularized by the programming language Lisp, which uses them for source code as well as data. In the usual parenthesized syntax of Lisp, an s-expression is classically defined as The second, recursive part of the definition represents an ordered pair, which means that s-expressions are binary trees. code examples
 * an atom, or
 * an expression of the form (x . y) where x and y are s-expressions.

Assignment
(set (if (eq a b) 'c 'd) 'foo) will either set c to foo or set d to foo, depending on the outcome of the test (eq a b). set returns value as its result.
 * set allows alteration of the value of a dynamic (special) variable. set causes the dynamic variable named by symbol to take on value as its value.
 * Only the value of the current dynamic binding is altered; if there are no bindings in effect, the most global value is altered. For example,


 * set cannot alter the value of a local (lexically bound) variable. The special form setq is usually used for altering the values of variables (lexical or dynamic) in programs.
 * set is particularly useful for implementing interpreters for languages embedded in Lisp.

Math Functions
code The function -, when given one argument, returns the negative of that argument. The function -, when given more than one argument, successively subtracts from the first argument all the others, and returns the result. For example, (- 3 4 5) => -6.
 * + &rest numbers will the sum of the arguments. If there are no arguments, the result is 0, which is an identity for this operation.
 * - number &rest more-numbers

COND
The template for a cond expression looks like this:

(cond     body...) where the body is a series of lists.

Written out more fully, the template looks like this:

(cond     (first-true-or-false-test first-consequent)      (second-true-or-false-test second-consequent)      (third-true-or-false-test third-consequent)       ...      T final-consequent)

When the Lisp interpreter evaluates the cond expression, it evaluates the first element (the car or true-or-false-test) of the first expression in a series of expressions within the body of the cond.

If the true-or-false-test returns nil the rest of that expression, the consequent, is skipped and the true-or-false-test of the next expression is evaluated. When an expression is found whose true-or-false-test returns a value that is not nil, the consequent of that expression is evaluated. The consequent can be one or more expressions. If the consequent consists of more than one expression, the expressions are evaluated in sequence and the value of the last one is returned. If the expression does not have a consequent, the value of the true-or-false-test is returned.

The cond statement's final condition needs to be a true condition so that it can evaluate and return the final-consequent, even if all of the other true-or-false-tests' fail.

Written using cond, the triangle function looks like this:

(defun triangle-using-cond (number)      (cond ((<= number 0) 0) ((= number 1) 1) (T (+ number (triangle-using-cond (1- number)))) )    )

In this example, the cond returns 0 if the number is less than or equal to 0, it returns 1 if the number is 1 and it evaluates (+ number (triangle-using-cond (1- number))) if the number is greater than 1.

= Week 6 - Language concepts: variable types, scope, implemntation & parameter passing = Content authors (Group #5) Bridget Franciscovich and Aashirya Kaushik

Outline by Bridget Franciscovich
 * What are variables in computer Programming?
 * How are variables represented (it's three values: address, size, information)
 * Variable types - what does type mean for a variable?
 * Why is variable type important? (why variable types are important - memory reservation...)
 * Strong vs weak typed language (definition with examples)
 * Dynamic vs static typed language (definition with examples)
 * Data types (each with definition and a simple example if needed)
 * Primitive data types
 * Discuss/list common ones (i.e. int, flat, char, bool)
 * Complex data types
 * i.e. structs/records, classes
 * Variable scope - define and discuss scope levels
 * Global vs local scope
 * Parameterization
 * Variable scope in OOP (reasoning behind using local and global in OOP)
 * Parameter Passing
 * Pass by value
 * Provide example in Java
 * Pass by reference
 * Provide example in C++
 * Briefly mention others like In/out but don't discuss them

Variables in Computer Programming
A variable is a symbolic name for (or reference to) information. The variable's name represents what information the variable contains. They are called variables because the information represented by the variables can change but the operations on the variable remain the same. Variables in computer programming are analogue to "Buckets" or "Envelopes" where information can be maintained and referenced. On the outside of the bucket is a name. When referring to the bucket, we use the name of the bucket, not the data stored in the bucket.

Variable Representation
Variables have three values associated with them: its address, its size in memory, and information it holds.

Address
All computers have memory, also known as RAM (random access memory). For example, your computer might have 16 or 32 or 64 megabytes of RAM installed right now. RAM holds the programs that An address-of operator is a mechanism within C++ that returns the memory address of a variable. These addresses returned by the address-of operator are known as pointers, because they "point" to the variable in memory.

Size
variable-length array (VLA), also called variable-sized, runtime-sized, is an array data structure whose length is determined at run time, instead of at compile time. The specifics of variable allocation and the representation of their values vary widely, both among programming languages and among implementations of a given language. Many language implementations allocate space for local variables, whose extent lasts for a single function call on the call stack, and whose memory is automatically reclaimed when the function returns. More generally, in name binding, the name of a variable is bound to the address of some particular block (contiguous sequence) of bytes in memory, and operations on the variable manipulate that block. Referencing is more common for variables whose values have large or unknown sizes when the code is compiled. Such variables reference the location of the value instead of storing the value itself, which is allocated from a pool of memory called the heap.

Bound variables have values. A value, however, is an abstraction, an idea; in implementation, a value is represented by some data object, which is stored somewhere in computer memory. The program, or the runtime environment, must set aside memory for each data object and, since memory is finite, ensure that this memory is yielded for reuse when the object is no longer needed to represent some variable's value.

Objects allocated from the heap must be reclaimed—especially when the objects are no longer needed. In a garbage-collected language (such as C#, Java, Python and Lisp), the runtime environment automatically reclaims objects when extant variables can no longer refer to them. In non-garbage-collected languages, such as C, the program (and the programmer) must explicitly allocate memory, and then later free it, to reclaim its memory. Failure to do so leads to memory leaks, in which the heap is depleted as the program runs, risks eventual failure from exhausting available memory.

When a variable refers to a data structure created dynamically, some of its components may be only indirectly accessed through the variable. In such circumstances, garbage collectors (or analogous program features in languages that lack garbage collectors) must deal with a case where only a portion of the memory reachable from the variable needs to be reclaimed.



Information
In programming, a variable is a value that can change, depending on conditions or on information passed to the program. Typically, a program consists of instruction s that tell the computer what to do and data that the program uses when it is running.

What does a variable type mean?
When you declare a variable in a program, you specify its type, which can be chosen from integral, floating point, decimal, boolean or nullable types. The type tells the compiler how to handle the variable and check for type errors. The type also determines the position and size of the variable's memory, the range of values that it can store and the operations that can be applied to the variable.

A few basic variable types include (example from C/C++):

 * int - Int is short for "integer." It is used to define numeric variables holding whole numbers. Only negative and positive whole numbers can be stored in int variables.


 * null - A nullable int has the same range of values as int, but it can store null in addition to whole numbers.


 * char - A char type consists of Unicode characters—the letters that represent most of the written languages.


 * bool - A bool is a fundamental variable type that can take only two values: 1 and 0, which correspond to true and false.


 * float, double and decimal - these three types of variables handle whole numbers, numbers with decimals and fractions. The difference in the three lies in the range of values. For example, double is twice the size of float, and it accommodates more digits.

Strong vs Weak typed language
The main difference between a strongly typed language and a weakly typed one is that a weakly typed one makes conversions between unrelated types implicitly, while a strongly typed one typically disallows implicit conversions between unrelated types.

Furthermore a strongly typed language requires an explicit conversion (by using the cast operator) between related types, when there is possibility of data loss, while a weakly typed one would carry out the conversion regardless.

Examples
my $test; $test = 1; #Test variable as integer $test = "hello"; #Test variable as a string now boolean isDog;
 * Perl is a weakly typed language, you can declare a variable, but it does not require you to classify the type of variable. In the example below $test is a variable that can be used as an integer or string.
 * Java is a strongly typed programming language because every variable must be declared with a data type. A variable cannot start off life without knowing the range of values it can hold, and once it is declared, the data type of the variable cannot change.The variable isDog will always have boolean as its datatype. The value for boolean can either be True or False.

Dynamically typed languages
A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc. This means that you as a programmer can write a little quicker because you do not have to specify types every time (unless using a statically-typed language with type inference). Example: Perl, Ruby, Python

Static typed language
A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is (e.g.: Java, C, C++) The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early s

Data types
A data type, in programming, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error. A string, for example, is a data type that is used to classify text and an integer is a data type used to classify whole numbers.

Primitive Data type
Primitive datatypes are predefined by the language and named by a keyword. There are four main primitive data types and they are as follows:
 * int - Int data type is a 32-bit signed two's complement integer.
 * Integer is generally used as the default data type for integral values unless there is a concern about memory.
 * The default value is 0
 * Example: int a = 100000, int b = -200000
 * double - double data type is a double-precision 64-bit IEEE 754 floating point
 * This data type is generally used as the default data type for decimal values.
 * Double data type should never be used for precise values such as currency
 * Default value is 0.0d
 * Example: double d1 = 123.4
 * char - char data type is a single 16-bit Unicode character
 * Char data type is used to store any character
 * Example: char letterA = 'A'
 * boolean- boolean data type represents one bit of information
 * There are only two possible values: true and false
 * This data type is used for simple flags that track true/false conditions
 * Example: boolean one = true

Complex data types

 * A complex data type is a data type that does not fall into the traditional field structure, alpha, numeric, dates, integers, etc. and either the client application or some middleware is required to process the data, Examples of complex data types are
 * Images
 * Videos
 * Maps
 * Word Processing Documents
 * Time-series


 * A struct in the C programming language is a composite data type (or record) declaration that defines a physically grouped list of variables to be placed under one name in a block of memory, allowing the different variables to be accessed via a single pointer, or the struct declared name which returns the same address. The struct can contain many other complex and simple data types in an association, so is a natural organizing type for records like the mixed data types in lists of directory entries reading a hard drive (file length, name, extension, physical (cylinder, disk, head indexes) address, etc.), or other mixed record type (patient names, address, telephone... insurance codes, balance, etc.).

MyObject    anObject = new MyObject;   // legal MyObject     anotherObject = null;   // legal MyObject     stillAnotherObject = 0;   // illegal
 * Classes refer to data types that define methods and data. Internally, the Java typically implements a class type object as a set of pointers to methods and data. Variables defining class types can refer only to instances of the class types or to the null reference, as the following snippet demonstrates:

Variable Scope
Scope of a variable is defined as the extent of the program code within which the variable can we accessed or declared or worked with. In simpler words it is described as the visibility of the variable. The two main types of variable scope are:

Local Scope
Variables defined within a function or block are said to be local to those functions. Local variable is a variable with Local Scope void func{ // this variable is local to the // function func and cannot be    // accessed outside this function int age=18; } int main{ cout<<"Age is: "<<age; return 0; }
 * Anything between ‘{‘ and ‘}’ is said to inside a block.
 * Local variables do not exist outside the block in which they are declared, i.e. they can not be accessed or used outside that block.
 * Declaring local variables: Local variables are declared inside a block.
 * Example :

This will give an error saying "age is not defined/declared in this scope" because the variable age was declared within the function func so it is local to that function and not visible to portion of program outside this function.

Global Scope
Global Variables can be accessed from any part of the program. Global variable is a variable with Global Scope // global variable int a = 5; // global variable accessed from // within a function void display {   cout<<a<<endl; } // main function int main {   display; // changing value of global // variable from main function a = 10; a; }
 * Declaring global variables: Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program.
 * Example

In the above example, the variable “global” is declared at the top of the program outside all of the functions so it is a global variable and can be accessed or updated from anywhere in the program.

Parameterization
The scope of a formal parameter is the section of code that can see the parameter. The scope of a formal parameter is the body of its method. For example, the scope of amount is the body of its method. The toString method cannot see amount because it is outside the scope of amount. The compiler will not compile this modified program as seen in the example: class CheckingAccount { . . . .  private int balance;

. . . . public void processDeposit( int amount ) { // scope of amount starts here balance = balance + amount ; // scope of amount ends here }

// modified toString method public String toString {   System.out.println( balance + "\t" + amount );  // outside of the scope of amount }

}

A parameter is accessed and modified but it is still local, however, it can be modified outside of the function. C++ has by reference the parameter can pass by the value for example, void do(int value) C++ also has pass by reference where the count will be modified by count.

Local versus Global Variable Scope in OOP
Local variables are declared inside a function and can be used only inside that function. It is possible to have local variables with the same name in different functions. Even if the name is the same, they are not the same. It's like two people with the same name. Local variables would always help you. Global Scope variables can be useful because all fucntions can call them and can be used when multiple functions need to access the data or write to an object. For example, if you had to pass data or a reference to multiple functions such as a single log file, a connection pool, or a hardware reference that needs to be accessed across the application. Local Scope variables are useful to use because the single change in the variable will not have an effect on the overall functionality of the program. As it is localed in one function, as per its name, and any changes to the variable will only change the functionality of the one function.

Parameter passing
The mechanism used to pass parameters to a procedure (subroutine) or function. The most common methods are to pass the value of the actual parameter (call by value), or to pass the address of the memory location where the actual parameter is stored (call by reference). The latter method allows the procedure to change the value of the parameter, whereas the former method guarantees that the procedure will not change the value of the parameter.

Pass by value
In this approach we pass copy of actual variables in function as a parameter. Hence any modification on parameters inside the function will not reflect in the actual variable. For example in Java: public class Main {   public static void main(String[] args) {       int x = 5; change(x); System.out.println(x); }   public static void change(int x)    { x = 10; } } We pass an int to the function “change” and as a result the change in the value of that integer is not reflected in the main method. Java creates a copy of the variable being passed in the method and then do the manipulations.

Pass by reference
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. This example shows how arguments are passed by reference. The reference parameters are initialized with the actual arguments when the function is called.

void swapnum(int &i, int &j) { int temp = i; i = j;  j = temp; } int main(void) { int a = 10; int b = 20; swapnum(a, b); printf("A is %d and B is %d\n", a, b); return 0; }

When the function swapnum is called, the values of the variables a and b are exchanged because they are passed by reference. The output is: A is 20 and B is 10

Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument. When the called function read or write the formal parameter, it is actually read or write the argument itself. The difference between pass-by-reference and pass-by-value is that modifications made to arguments passed in by reference in the called function have effect in the calling function, whereas modifications made to arguments passed in by value in the called function can not affect the calling function. Use pass-by-reference if you want to modify the argument value in the calling function. Otherwise, use pass-by-value to pass arguments.

IN/OUT
With In/Out you provide a value that is used inside the function, and the function modifies it to inform you about something that happened inside the function.

= Week 7 (& 6) - An overview of Scratch = Content authors (Group #6) Faruk Durakovic and Orevaoghene Omu

Outline by Oreva Omu
 * What is a visual Programming Language
 * brief description of its paradigm
 * advantages and disadvantages of Scratch
 * A tutorial on Scratch with example
 * pictorial view of Scratch Window
 * explain Scratch block types.
 * i.e.Scratch data types.
 * functionalities of each pane: list categories and describe
 * i.e. the 8 main for 1.4 (maybe more for 2.0)
 * short code example for each category
 * Note: give a feel of the language without being complete
 * what are sprites - how do they compare to objects
 * Complexity in Scratch
 * Race Conditions
 * How to avoid Race Condition
 * Concurrency issues

What is a Visual Programming Language
In most programming languages, programs are created through manipulation of texts which represents the code for that program. A Visual Programming Language(VPL) creates graphical representation of common language primitives and allows users create programs through manipulation of these graphical primitives rather than specifying them through textual representation.

Some VPL examples includes AgentSheets, AgentCubes, AppInventor, Bubble, Lava, Scratch, STELLA, Snap!, Subtext.

Brief description of its paradigm
A VPL allows programming with visual expressions, spatial arrangements of text and graphic symbols, used either as elements of syntax or secondary notation. VPLs may be further classified, according to the type and extent of visual expression used, into icon-based languages, form-based languages, and diagram languages.

The general goal of VPLs is to make programming more accessible to novices and to support programmers at three different levels:

Syntax: VPLs use icons/blocks, forms and diagrams trying to reduce or even to completely eliminate the potential of syntactic errors helping with the arrangement of programming primitives to create well-formed programs. Non VPLs examples would be spell check in word processors underlining or even auto correcting individual words or grammar.

Semantics: VPLs may provide some mechanisms to disclose the meaning of programming primitives. This could include help functions providing documentation functions built-in to programming languages.

Pragmatics: VLPs support the study of what programs mean in particular situations. This level of support allows users to put artifacts created with a VPL into a certain state in order to explore how the program would react to that state. Examples: In AgentSheets or AgentCubes users can set games or simulations into a particular state in order to see how program would react.

The "visual languages" (Visual Basic, Visual C#, Visual J#, etc.) of the Microsoft Visual Studio IDE are not visual programming languages. All of these languages are textual and not graphical. The MS Visual Studio is a visual programming environment however.

Parsers for visual programming languages can be implemented using graph grammars.

Advantages

 * Scratch is easy to use.
 * Scratch is a good introduction to programming for kids . It keeps them interested, motivated by challenged by allowing them create animation, stories and games which can be shared online.
 * Scratch has some features of Object-Oriented programming.
 * Scratch is free to use.
 * Although it is meant for kids, ages 8 - 16, it could be used by people of all ages.
 * Scratch is used in more than 150 different countries and available in more than 40 languages.

Disadvantages

 * Very limited built-in Sprites and Backdrops.
 * Other Scratchers can take use your entire project to make their own project. This is called remixing in Scratch. Copyright is optional.
 * Requires email to register which some kids might not have, therefore making it hard for them to begin learning n their own.

A tutorial on Scratch with example
SCRATCH is a programming language that lets you create your own interactive stories, animations, games, music, and art. Scratch is available online at https://scratch.mit.edu/. Visit the link to get started. An account isn't required to start using it but it is required in order to manage your projects. To run your projects effectively on Scratch you would need a recently browser version (Chrome 35 or higher, Internet Explorer 8 or higher, Firefox 31 or later), with a more recent version of Adobe Flash Player (10.2 or higher).

Pictorial view of Scratch Window
When you visit the Scratch URL (link in section above), you should see a similar homepage to this.

Use the "Join Scratch" button at the top right corner to create an account or use the "Sign In" button to sign in with your already created username and password. You can start new projects with the "Create" button at the top left corner of page. Now let's see what the editor window looks like when you click the "Create" button.



Areas labelled A, B, C, D are the most important areas of the scratch windows. We would go through what each areas represent in addition to other areas in the Scratch environment.

Area A - the SCRIPT area: A Script is a group of connected blocks that execute from top to bottom. The Script area is where you organize your blocks, arranging them in the order in which they should flow.

Area B - the BLOCK area: Blocks are colored pieces that fit into each other to make a program. Blocks of the same colors are related blocks, for instance, the blue color blocks are meant for motion.

Area C - the STAGE area: The Stage is where you see your output when you run your scripts. Scripts can be tested by double clicking them or connecting them to event blocks, and then run when those events are performed.

Area D - the SPRITE area: A Sprite is a character in Scratch. A Sprite could have different costumes, sounds, and scripts. You can either use default Sprites in Scratch or create your own Sprite.

Other areas of the scratch windows are:
 * The block tabs: which allow you switch between categorized blocks.
 * The backdrop area: which allows you create or modify a backdrop.
 * The sprite tabs: which allows you create a new Sprite or edit an exiting one.
 * Costume area: Which allows you change the appearance of the Sprite, or add more costumes.
 * Sound area: which allows you add sound to your project.
 * Backpack area: which allows users to drop costumes, sounds, sprites, scripts from other projects and reuse it in other places by simply dragging them back.

Data types in Scratch
A variable is a changeable value recorded in Scratch's memory. Variables can only hold one value at a time, unlike lists. These values can be either numbers or strings — any text. Clicking on an isolated variable in the scripts area displays a small bubble reporting the value of the variable. Unlike many other programming languages, variables must be created prior to when the project actually runs. This only results in a small amount of RAM being used to store the value for use when the project actually runs. Variables are created with the Make a variable button in the Data category.

There are five different blocks relating to variables:


 * variable: displays the value of a variable.
 * set variable: sets a chosen variable to a specified value.
 * change variable: changes the value of a chosen variable by a specified amount.
 * show variable: shows the specified variable in the stage area.
 * hide variable: hides the specified variable in the stage area.

There are two variable types - Global variables and Local variables labelled in Sprite as For all sprites and For this sprite only

Global variables can be read and changed by any sprite, or the Stage. All variables are stored in RAM. Local variables are created the same way as global, but another option is selected in the variable creation dialog, "For this sprite only". Personal variables can only be changed by their owner, but can be read by other sprites.

A list is made of items — each item like a variable. Lists can be useful when many variables are needed or when the amount of memory that needs to be stored can not be determined by the programmer before the project is run.

Block Categories and Functionalities

 * Motion
 * Description: Used to control the movement of Sprites.
 * Functionalities
 * move steps : The block moves its sprite forward the specified amount of steps in the direction it is facing. A step is equal to a one-pixel length. The Default Value is 10 and can be replaced by any Number. The block actually uses Trigonometry to move in the proper direction, as that is how a computer handles it.
 * turn degrees : The blocks turn their sprite the specified amount of degrees clockwise or counter-clockwise (depending on which block is used); this changes the direction the sprite is facing. The blocks use the 360 degrees in a circle. The Default Value is 15 and can be replaced by any number (360+x displays the same as 0+x).
 * point in direction  : The block points its sprite in the specified direction; this rotates the sprite. The blocks use the 360 degrees in a circle. The Default Value is 90 and can be replaced by any Number (360+x displays the same than 0+x).
 * point towards  : The block points its sprite towards the mouse-pointer or another sprite depending on its costume center; this changes the sprite's direction and rotates the sprite.
 * go to x: y: : The block sets its sprite's X and Y position to the specified amounts. This block has no animation in its movement. This block is used whenever a sprite needs to jump to another spot.
 * go to  : The block sets its sprite's X and Y position to that of the mouse-pointer, an arbitrary coordinate, or another sprite.
 * glide secs to x: y: : The block moves its sprite steadily to the specified X and Y position in the specified amount of seconds - this is like pointing the sprite in a direction and repeatedly using Move  Steps, but with more precision. A disadvantage of the glide block, however, is that it pauses the script while the sprite is moving, preventing the script from doing other things while the sprite is gliding.
 * change x by  : The block moves its sprite costume center's X position by the specified amount. The x axis ranges from -240 to 240.
 * set x to  : The block changes the selected sprite's X position to a specified value.
 * change y by  : The block moves its sprite's Y position by the specified amount.
 * set y to 0 : The block sets its sprite's Y (up and down) position to the specified amount.
 * if on edge, bounce : The block checks to see if its sprite is touching the edge of the screen with the move steps block — and if it is, the sprite will point in a direction that mirrors the direction from which it was coming. It uses a line perpendicular to the edge to determine the reflection angle.
 * set rotation style  : The block changes the Rotation Style of the sprite in-project.
 * x position : The block holds its sprite's X position.
 * y position : The block holds its sprite's Y position.
 * direction : The block holds its sprite's direction, measured in degrees — this direction value is what is used with the Point in Direction block.
 * Example
 * The following example takes the sprite to the center of the stage, moves it 10 steps and turns it 90 degrees.


 * Looks
 * Description: Used to define a Sprite's appearance.
 * Functionalities
 * <font color=#8A55D7>say for  secs : The block displays a speech bubble with the specified text for the sprite that runs it, which appears on the screen for the specified amount of seconds.
 * <font color=#8A55D7>say  : The block gives its sprite a speech bubble with the specified text — the speech bubble stays until an another speech or thought block is activated, or the stop sign is pressed. This block immediately moves on to the next block when it is activated, unlike the say for  secs block.
 * <font color=#8A55D7>think for  secs : The block give its sprite a thought bubble with the specified text, which stays for the specified amount of seconds.
 * <font color=#8A55D7>think  : The block gives its sprite a thought bubble with the specified text. The thought bubble stays until a speech or thought block with its text block empty is activated, or the stop sign is pressed.
 * <font color=#8A55D7>show : If the block's sprite is hidden, it will show the sprite — if the sprite is already showing, nothing will change.
 * <font color=#8A55D7>hide : If the block's sprite is shown, it will hide the sprite — if the sprite is already hidden, nothing happens.
 * <font color=#8A55D7>switch costume to  : The block changes its sprite's costume to a specified one.
 * <font color=#8A55D7>next costume : The block changes its sprite's costume to the next one in the costumes pane, but if the current costume is the last in the list, the block will loop to the first.
 * <font color=#8A55D7>switch backdrop to  : The block changes the Stage's backdrop to the specified one.
 * <font color=#8A55D7>change effect by  : The block changes the specified effect on its sprite by the specified amount. There are seven different effects to choose from: color, fisheye, whirl, pixelate, mosaic, brightness and ghost.
 * <font color=#8A55D7>set effect to  : The block sets the specified effect on its sprite to the specified amount. There are seven different effects to choose from: color, fisheye, whirl, pixelate, mosaic, brightness, and ghost
 * <font color=#8A55D7>clear graphics effect : This block resets all 7 graphic effects (color, fisheye, whirl, pixelate, mosaic, brightness and ghost) on its sprite.
 * <font color=#8A55D7>change size by  : The block changes its sprite's size by the specified amount. The default sprite size is 100; size values below that percentage are for shrunken sprites, and size values above it are for overlarge sprites.
 * <font color=#8A55D7>set size to % : The block sets its sprite's size to the specified amount. The default sprite size is 100%; anything lower than that will decrease the size of the sprite on the stage, and anything above will increase the size of the sprite on the stage.
 * <font color=#8A55D7>go to front : The block will place a sprite in front of all other sprites. It does this by changing the sprite's layer value.
 * <font color=#8A55D7>go back layers : The block changes its sprite's layer value by the specified amount. This block moves the layer value back, and not forward. To move it forward instead, a negative number can be used.
 * <font color=#8A55D7>costume # : The block holds its sprite's current costume number.
 * <font color=#8A55D7>backdrop name : The block holds the current backdrop name.
 * <font color=#8A55D7>size : The block holds its sprite's size.
 * Example
 * The following example switches the stage backdrop, switches the costume of the sprite, changes the color by 25 and makes the sprite say "Hello Scratchers".


 * Sound
 * Description: used to control sound.
 * Functionalities
 * <font color=#BB42C3>play sound  : The block will play the specified sound, with no pause to its script.
 * <font color=#BB42C3>play sound until done : The block will play the specified sound, pausing its script until the sound has finished playing.
 * <font color=#BB42C3>stop all sounds : The block will stop any sounds currently being played on all sprites and the Stage.
 * <font color=#BB42C3>play drum for  beats : The block will play the specified instrument for the specified amount of seconds using a MIDI drumset. Even though the block uses the word "drum", the choices in the drop-down menu are many different percussion instruments including drums, triangle, bongos, cowbell, vibraslap, and various idiophones.
 * <font color=#BB42C3>rest for beats : The block pauses its script for the specified amount of beats, which can be a decimal number.
 * <font color=#BB42C3>play note for  beats : The block will play the specified note with a set MIDI instrument for the specified amount of beats.
 * <font color=#BB42C3>set instrument to  : The block changes the set MIDI instrument that the Play Note for  Beats block will play. (The Play Drum  for  Beats block is not affected by the Set Instrument to  block; it has its own instruments in a drop-down menu.) One sprite can "play" only one instrument at a time. In order to play multiple instruments at once, it is necessary to have multiple sprites or clones of a single sprite.
 * <font color=#BB42C3>change volume by  : The block changes the volume of a sprite by the specified amount. This only affects the sprite (or the Stage) that the block is in.
 * <font color=#BB42C3>set volume to % : The block sets its sprite's volume to the specified amount. It only affects the sprite (or the Stage) that the block is in.
 * <font color=#BB42C3>volume : The block holds a sprite's or the Stage's volume.
 * <font color=#BB42C3>change tempo by  : The block changes the project's tempo by the specified amount. Changing the tempo affects how long the Play Drum for  Beats block and the Play Note  for  Beats block will play, due to the tempo affecting the length of a beat.
 * <font color=#BB42C3>set tempo to bpm : The block sets the Scratch project's tempo, or speed, to the specified amount, using the unit "bpm", or "beats per minute".
 * <font color=#BB42C3>tempo : The block holds the Scratch project's tempo.
 * Example
 * The following example sets instrument to piano and plays "do re mi" notes with 0.5bpm


 * Pen
 * Description: used to control pen and drawing in Scratch.
 * Functionalities
 * <font color=#006400>clear : The block removes all marks made by the pen or stamps.
 * <font color=#006400>stamp : When used in a script, the Sprite will produce a bitmap image of itself, which is stamped onto the Stage. The image cannot be programmed, as it is not considered a sprite. Like other pen blocks, the stamp block will not stamp over other sprites.
 * <font color=#006400>pen down : The block will make its sprite continuously pen a trail wherever it moves (until the Pen Up block is used). The color, width, and shade of the trail can be changed with other independent blocks.
 * <font color=#006400>pen up : If a sprite is currently using the pen feature because of the Pen Down block, the block will stop it from continuing. If the pen feature is not being used, the block will have no effect.
 * <font color=#006400>set pen color to  : The block sets the pen's color to the color chosen with the block's color-picker (eyedropper tool). To select a color (in the non-value-entry block), one must click on the color box and then click anywhere in the Scratch program to change the color with the eye-dropper.
 * <font color=#006400>change pen color by  : The block increments or decrements the pen's color by the specified value. The color value holds 200 different values of colors (0 to 199, inclusive), so color 200 is the same as color 0. In other words, changing the pen color by 200 color will not change the appearance of the pen.
 * <font color=#006400>set pen color to  : The block sets the pen's color to the hue chosen with the argument. A 200 pen color value is the same color as a 0 pen color value; in other words, if you change the pen color by 200, the color still looks the same.
 * <font color=#006400>change pen shade by  : The block changes the pen's shade by the specified amount.
 * <font color=#006400>set pen shade to  : The block sets the pen's shade to the specified amount. A 200 pen shade value is the same shade as a 0 pen shade value. In other words, if you change the pen shade by 200, the shade still looks the same.
 * <font color=#006400>set pen size to  :The block sets the pen's size to the specified amount.
 * <font color=#006400>change pen size by 1 : The block changes the pen's size by the specified amount.
 * Example
 * The following example draws a house with a roof


 * Data
 * Description: allows users create variables and lists.
 * Functionalities
 * make a variable: used to create variables and blocks that are used to hold values and strings in those variables, as well as display them.
 * <font color=#EE7D16> : The block simply holds its variable. This block can be displayed in the Stage area.
 * <font color=#EE7D16>set to  : The block will set the specified variable to the given value: a string or number.
 * <font color=#EE7D16>change by  : The block will change the specified variable by a given amount. If the variable is a string and not a number, it is set to the quantity the variable was to be changed by (casting the string to 0).
 * <font color=#EE7D16>show variable  : The block shows the specified variable.
 * <font color=#EE7D16>hide variable  : The block hides the specified variable.
 * make a list:
 * list : used to create lists and blocks that are used to hold values and strings in those lists, as well as display them.
 * add to  : The block adds an item onto the end of the specified list, the item containing the given text
 * delete of  : The block can delete the item inputted, the last item, or all items of the specified list depending on the option selected.
 * insert at  of  : The block inserts an item containing the given text into the list, at the given position. All values below the inserted item are passed onto the item beneath them; the last item's value is placed in a new item at the end of the list.
 * replace item of  with  : The block replaces the specified item; in other words, it changes the item's content to the given text.
 * item of  : The block reports the value of the specified entry in a specified list.
 * length of  : The block reports how many items a list contains.
 *  contains ? : The block checks if the first parameter's text contains the second parameter's text—if it does, the block reports true; otherwise, it reports false, and this is case-insensitive.
 * show list  : The block shows the specified list in the Stage area.
 * hide list : The block hides the specified list in the Stage area.
 * Example
 * The following add student names to a list, displays it and makes the sprite say the list.


 * Events
 * Description: used to trigger scripts based on events.
 * Functionalities
 * <font color=#EE7D16>When Green Flag Clicked : Scripts that wear this block will activate once the Green Flag has been clicked — these scripts can activate other scripts and enable the entire program. Without this block, the only way a project could run would be that it would sense the pressing of a key or clicking a sprite; the project would only last until all scripts depending on the starting scripts have ended. This block is also the most used block in all of Scratch.While it is fully possible to script projects without this block, it is not recommended; the Flag represents the start of a project, so this block will sense when the project has been started.
 * <font color=#EE7D16>When key pressed :  Scripts placed underneath this block will activate when the specified key is pressed. The keys that can be sensed with this block include the entire English alphabet (a - z), the number keys ( 0 - 9), the arrow key, and the space key. In the Experimental Viewer, the ↵ Enter key (or return key on Macs) could also be sensed.
 * <font color=#EE7D16>When this sprite clicked : Scripts that wear the block will activate once its sprite or clone of the sprite is clicked. Contrary to its definite name, the block will also execute the clone's script when the clone is clicked on. If a sprite is has been hidden by the hide block, when its location is clicked on, the script under the When This Sprite Clicked block will not activate.
 * <font color=#EE7D16>When backdrop switches to  : Scripts that wear this block will be triggered once the specified backdrop has been switched to on the Stage.
 * <font color=#EE7D16>When >  : It starts the script below it when a value (chosen by the dropdown menu) is greater than another value (entered by the number input). The available options are loudness, timer, and video motion.
 * <font color=#EE7D16>When I receive  : Scripts that begin with this block will be invoked once the specified broadcast has been sent by a calling script. If a Forever block is sending the broadcast faster than the attached script can finish running, the script will restart without reaching the blocks at the end. This can be avoided by using Broadcast and Wait.
 * <font color=#EE7D16>broadcast  : This is a block which sends a broadcast throughout the whole Scratch program. Any scripts in any sprites that are hatted with the When I Receive block that is set to a specified broadcast will activate. This broadcast block lets scripts send broadcasts without any waits in its script (unlike the Broadcast  and Wait block). Broadcasts are a good way to have sprites and scripts communicate.
 * <font color=#EE7D16>broadcast and wait : The block sends a broadcast throughout the whole Scratch project — any scripts that are halted with the When I Receive  block and are set to the broadcast will activate. This broadcast block lets scripts send broadcasts, and have them wait until all scripts activated by the broadcast end (unlike the Broadcast  block, which will let its script continue without it waiting for the scripts activated by the broadcast).
 * Example
 * The following example changes the color of the sprite when the sprite is clicked.


 * Control
 * Description: used to control scripts.
 * Functionalities
 * wait secs : The block pauses its script for the specified amount of seconds — the wait can also be a decimal number. This block is one of the most commonly used blocks; it is used whenever a sprite must wait for another action.
 * repeat 10 : Blocks held inside this block will loop a given amount of times, before allowing the script to continue. If a decimal is put in, the number is rounded up.
 * forever : Blocks held inside this block will be in a loop — just like the Repeat block and the Repeat Until  block, except that the loop never ends (unless the stop sign is clicked, the Stop All block is activated, or the stop script block is activated within the loop).
 * if then : The block will check its boolean condition. If the condition is true, the blocks held inside it will run, and then the script involved will continue. If the condition is false, the code inside the block will be ignored and the script will move on (unlike in the If Then, Else block). The condition is only checked once; if the condition turns to false while the script inside the block is running, it will keep running until it has finished.
 * if then else : The block will check its boolean condition: if the condition is true, the code held inside the first C (space) will activate, and then the script will continue; if the condition is false, the code inside the second C will activate (unlike the If Then block).
 * wait until : The block pauses its script until the specified boolean condition is true.
 * repeat until  : Blocks held inside this block will loop until the specified boolean statement is true, in which case the code beneath the block (if any) will execute. This loop is in similar nature to a while loop in some other programming languages.
 * stop all : stops other scripts in a sprite
 * when I start as clone : It activates in a clone when it gets created.
 * create clone of myself : It creates a clone of the sprite in the argument. It can also clone the sprite it is running in, creating clones of clones, recursively.
 * delete this clone : It deletes the clone it runs in. This block is the only way, besides clicking the Green Flag or Stop Sign, to delete clones. When a clone is created, you can use this block to delete it. (This will only delete the clone under the script starting with the "When I start as a clone" block.)
 * Example
 * The following example changes the backdrop to two if the current backdrop is one, else it changes it to one.


 * Sensing
 * Description: used to detect different objects of a project.
 * Functionalities
 * <font color=#2CA5E2>touching ? : The block checks if its sprite is touching the mouse-pointer, edge, or another sprite (a reporter block which returns the sprite's name, usually a variable can be used). If the sprite is touching the selected object, the block returns true; if it is not, it returns false.
 * <font color=#2CA5E2>touching color  : The block checks whether its sprite is touching a specified color. If it is, the block returns "true".
 * <font color=#2CA5E2>color is touching  : The block checks whether a color on its sprite is touching another color. If it is, the block returns "true".
 * <font color=#2CA5E2>distance to  : The block reports the Euclidean distance, in pixels, between it and the mouse-pointer or a specified sprite's costume center. If there is nothing in the drop-down insert of the block, or if a sprite that was deleted is still in the drop-down insert, it reports the distance as 0.
 * <font color=#2CA5E2>ask and wait : The block will make an input box (with the specified text above it) show at the bottom of the screen. Scratchers can input text into it and submit it, and the input is stored then in the Answer block. The Answer block automatically updates to most recent input.
 * <font color=#2CA5E2>answer : The block holds the most recent text inputted with the Ask and Wait block. When nothing has been inputted yet, the value will hold nothing.
 * <font color=#2CA5E2>key pressed? : The block checks if the specified key is pressed. If the key is being pressed, the block returns "true"; if it is not, it returns "false".
 * <font color=#2CA5E2>mouse down? : The block checks if the computer mouse's primary button is activated (being clicked and held).
 * <font color=#2CA5E2>mouse x : The block holds (reports) the mouse-pointer's current Mouse X.
 * <font color=#2CA5E2>mouse y : The block holds the mouse-pointer's current Mouse Y.
 * <font color=#2CA5E2>loudness : The block reports how loud the noise is that a microphone receives, on a scale of 0 to 100. To use this block, a microphone must be used, and so a message will appear on the screen, asking for permission to use the microphone. If you deny it, the block will report a loudness of 0 or -1. If you do not have a microphone, earbuds inserted into the microphone port work too.
 * <font color=#2CA5E2>video on  : It gets values of the video, either motion (on a scale of 1 to 100) or direction (which way the detected motion is going, measured on the same plane as sprite direction), on either the Stage, or the current sprite. It calculates the values based on "optical flow".
 * <font color=#2CA5E2>turn video  : It can turn the webcam on, off, or on flipped horizontally, depending on the argument.
 * <font color=#2CA5E2>set video transparency to % : It sets the transparency of the video stream to a certain value.
 * <font color=#2CA5E2>timer : The block starts at 0 when Scratch is launched and increases gradually; every second it will have increased by 1. This block is almost always used with the Reset Timer block — usually the timer must be reset at the beginning of a project for the Timer block to hold the right value.
 * <font color=#2CA5E2>reset timer : The block sets the timer's value back to 0.0. When this block is present, the project typically utilizes the Timer output block; usually the timer must be reset at the beginning of a project for the Timer block to hold the right value. There are no blocks that set the timer to a chosen value. The timer can only be specifically set to 0, using this block.
 * <font color=#2CA5E2> of  : The block will report a specified value of the specified sprite or the Stage. Here are the values that can be reported: X Position, Y Position, Direction, Costume/Backdrop number, Size, Volume, Variables local to the specified sprite
 * <font color=#2CA5E2>current  : It reports either the current local year, month, date, day of the week, hour, minutes, or seconds, depending on the argument. The block gets the data based on the user's computer's clock and set in 24-hour clock.
 * <font color=#2CA5E2>days since 2000 : It reports the amount of days (and fractions of a day) since 00:00:00 1 January 2000 (UTC). It is one of the two date/time blocks in Scratch. The other is current, which reports the date or time. Both these blocks can be worked in unison with one another for a variety of time-related scripts and projects.
 * <font color=#2CA5E2>username : It reports the username of the user viewing the project, which can be used for saving progress in a project, either with a variable encoder or cloud lists (once they are released with string-storage capabilities), as well as other purposes. If no user is signed in, this block returns the empty string.
 * Example
 * The following example asks for your name, wait's till you input your name and hit enter, then says your name.


 * Operators
 * Description: used to script mathematical and logical operations.
 * Functionalities
 * <font color=#5CB712>+ : The block adds two values and reports the result.
 * <font color=#5CB712>- : The block subtracts the second value from the first and reports the result.
 * <font color=#5CB712>* : The block multiplies the two values and reports the result. The numbers can be typed directly into the block, or Reporter blocks can be used instead. This block can be stacked inside itself - this can be used to fit more numbers in or calculate exponents.
 * <font color=#5CB712>/ : The block divides the second value from the first and returns the result. If the first value is not evenly divisible by the second, the reported value will have decimals. This block can be stacked inside itself — this can be used to fit more numbers in. Note, dividing by 0 in the online editor will return infinity, 0, or negative infinity. It depends on if the numerator is positive, 0, or negative; respectively. If attempted on an offline editor, it will give a Script Error and stops the script.
 * <font color=#5CB712>pick random to  : The block picks a pseudorandom number ranging from the first given number to the second, including both endpoints. If both numbers have no decimals, it will report a whole number. For example, if a 1 and a 3 were inputed, the block could return a 1, 2 or 3. If one of the numbers has a decimal point, even .0, it reports a number with a decimal. For example, if 0.1 and 0.14 were given, the output will be 0.1, 0.11, 0.12, 0.13, or 0.14. The numbers given with this block are not truly random — they are merely unpredictable. It is nearly impossible to generate truly random numbers using a computer.
 * <font color=#5CB712> <  : The block checks if the first value is less than the second value. If it is less, the block returns true; if not, it returns false. This block works with letters too, as well as numbers. In Scratch, letters at the top of the alphabet (e.g. a, b, c) are worth less than letters at the end (e.g. x, y, z).
 * <font color=#5CB712> =  : The block checks if the first value is equal to the other value. If the values are equal, the block returns true; if not, false. This block is not case-sensitive.
 * <font color=#5CB712> >  : The block checks if the first value is greater than the other value. If the second value is less, the block returns true; if not, it returns false. This block works with letters too, not just numbers. In Scratch, letters at the top of the alphabet (e.g. a, b, c) are worth less than letters at the end (e.g. x, y, z). Other rules of alphabetical order apply (e.g. zach > az).
 * <font color=#5CB712> and  : The block joins two boolean blocks so they both have to be true to return true. If they are both true, the block returns true; if they are not all true or none true, it returns false. This block can be stacked inside itself, which can be used to test more conditions.
 * <font color=#5CB712> or  : The block joins two boolean blocks so any one of them can be true to return true — if at least one of them is true, the block returns true; if neither of them are true, it returns false. This block can be stacked inside itself — this can be used to fit more booleans inside.
 * <font color=#5CB712>not  : The block checks if the boolean inside it is false — if it is false, the block returns true; if the condition is true, it returns false.
 * <font color=#5CB712>join  : The block concatenates, or "links" the two values together and reports the result — for example, if "hello" and "world" were put in the block, it would report "helloworld". To report "hello world", use either "hello " and "world" or "hello" and " world", with a space.
 * <font color=#5CB712>letter of  : The block reports the specified character of the given text. Even though the block says "letter", it will report all characters, including letters, numbers, symbols, and even spaces. The block is also useful to write the time or show scores.
 * <font color=#5CB712>length of  : The block reports how many characters the given string contains. Spaces count as characters in strings.
 * <font color=#5CB712> mod  : The block reports the remainder of the division when the first value is divided by the second. Negative numbers behave a little differently, because a remainder must always be positive. -10 mod 3 equals 2, not -1, because you have to multiply 3 by -4 to have any remainder at all.
 * <font color=#5CB712>round  : The block rounds the given number to the nearest integer. It follows the standard rules of rounding; decimals that are .5 or higher are rounded up, whereas decimals less than .5 are rounded down.
 * <font color=#5CB712> of  : The block performs a specified function on a given number and reports the result. The function can be changed by clicking the down arrow and selecting a new function from the drop-down menu.
 * Example
 * The following example picks a random number between 1 to 10 and checks if the number is 5, then displays a message.


 * More Blocks
 * Description: used to define custom blocks for Sprites.
 * Functionalities
 * Make a Block: Clicking this button brings up a dialogue asking for the block name. Then, enter the desired name as well as any inputs, and create the block. This category can technically have an unlimited amount of blocks, due to its blocks being user-created, but it has 1 type of Stack block and 1 type of Hat block (albeit modified).
 * Add an Extension: Scratch Extensions make it possible to connect Scratch projects with external hardware (such as LEGO WeDo or PicoBoard) or sources of information on the web. They add a collection of command and reporter blocks that can be used to interact with a particular device or data source. When an extension is enabled, its blocks appear in the "More Blocks" palette. To add an extension, go to the "More Blocks" category in the Scratch Editor and click "Add an Extension."

What are Sprites
Sprites, either user-created, uploaded, or found in the sprites library, are the objects that perform actions in a project. While the Stage can also be programmed in a project, most projects have at least one sprite as well because only sprites can move.

 What makes sprites objects 
 * You can access properties of sprites from other sprites.
 * Scratch 2.0 supports cloning, so dynamic sprite generation is possible.
 * A sprite could have it's variable or a shared variable with other sprites.

Complexity in Scratch
A race condition is Scratch is a situation that occurs when a script attempts to perform more than one operation at the same time. A Scrather has no say over what script runs first. For example if a sprite has two scripts with the "When Green Flag is clicked" block, which of those script runs first when the Green flag is clicked? You might end up having unexpected results because of this situation.

There are a few strategies you can use to avoid race conditions:


 * Avoid having more so much Events blocks than needed unless you can control them without it causing any problem.
 * There are blocks that could help to avoid race conditions.
 * Use the waits block often for scripts that might cause race conditions.
 * Use Scratch broadcasts to synchronize between sprites where necessary.
 * Use the broadcast and wait block to stops your script from moving ahead before getting results from other scripts.

= Week 9 - Language usage (utility, development) and the modern paradigm: OOP vs procedural = Content authors (Group #2) Andry Bintoro, Patrick McElhiney

Outline by Andry Bintoro
 * Language usage - utility vs development. - Include a brief discussion of what is implied here.
 * Development - elaborate on what makes a language this
 * What makes a language transform from utility to development
 * Utility - what makes a language this
 * Usage of web development and scripting languages
 * Comparison of the modern paradigm - OOP vs procedural.
 * Structure put on language and its purpose
 * Typed languages - restricts freedom to reduce error
 * how a struct (record) in procedural transformed into a class in OOP
 * Fundamentals structure of OOP
 * Encapsulation - reduces access to data (example)
 * Inheritance - adds hiarchy to data reuse (example)
 * Polymorphism - allows generality of data (example)
 * A quick contrast with pre-procedural paradigm - imperative
 * lacks structure - no subroutines
 * spaghetti logic - "go-to" dilema
 * An example of OOP vs Procedural would be good here

Language Usage (Utility vs. Development)

 * Utility in language usage means that it can be used in command line interface or graphical user interface as a tool. Utility program helps to manage, maintain and control computer resources. Operating systems typically contain the necessary tools for this, but separate utility programs can provide improved functionality. Utility software is often somewhat technical and targeted at users with a solid knowledge of computers.
 * Development in language usage means that the programming language is used to create development for other software. For example, one language can be the foundation of other languages. TypeScript is built upon the JavaScript framework and libraries. As a matter of fact, the development is used whenever software developers feel the need to create or recreate a new language to satisfy the requirements of an objective.

Utility

 * What makes a language this?
 * Utility is what makes programming language beneficial or useful, especially through being able to perform several function. Programming language that helps manage, maintain and control computer resources are considered utility language. For example, in computers, a utility is a small program that provides an addition to the capabilities provided by the operating system. In some cases, utility is a special and nonessential part of the Operating System. The print "utility" that comes with the operating system is an example.


 * In more detail, OS X Terminal opens up a world of powerful UNIX utilities and scripts. diskutil is a command line interface (CLI) to the Disk Utility app that comes with OS X, but can do more than the Graphical User Interface (GUI) - such as filling a disk with zeroes or random data. Simply type diskutil list to see the path names of disks and removable media attached to your machine, and then point the command at the volume you want to operate on. This is very similar in LINUX, with the command fdisk.

In web development,
 * Usage of web development and scripting languages

Development

 * What makes a language this?


 * What makes a language transform from utility to development?

Comparison of the Modern Paradigm (OOP vs. Procedural)
Computer programs consist of modules, which are components of a program that can be developed and tested separately. Modules are then assembled to form a complete program when they are being compiled or interpreted. In Procedural languages, such as C, modules are referred to as procedures, which are a sequence of statements. For an example, in C, procedures are made up of a sequence of imperative statements which include assignment statements, tests, loops and sub-procedure invocations. Procedures are basically just functions that map arguments to return statements.

The design method for modules used in Procedural programming is called the "Top Down Design". This means that you begin with a problem, or procedure, and systematically break it down into sub problems, or sub procedures. This is referred to as functional decomposition, which continues until a sub problem is solved by the corresponding sub procedure.

The difficulties with using this programming paradigm, is that software maintenance can be difficult and time consuming. Changes to the “main” procedure of a procedural program, referred to as the top of the program, cascade to the sub procedures of main, and the sub-sub procedures, etc. in a way that the changes could impact all of the procedures in the entire structure of the program.

An alternative to Procedural programming is Object Oriented Programming (OOP), which addresses the difficulties with the Procedural paradigm. In OOP, the “main” modules in a program are classes, rather than procedures. The object-oriented approach allows you to create classes, which execute instances of themselves which are referred to as objects.

Typed languages
Typed languages refers to the kind of typing system a programming language uses for defining variables, return values, and function calling. A weakly typed, or loosely typed language, is one that has looser typing rules that may result in unpredictable results, or could even perform implicit type conversion at runtime. A strongly typed language is one that has stricter typing rules at compile time, which usually significantly reduces the number of errors and exceptions that are likely during compilation. An example of a weakly typed language is JavaScript, which allows you to assign literally any value to any variable – whether it be an int, float, Boolean, string, or other data types, without having to specifically define that data type with the variable. This is because JavaScript has built-in functionality that allows it to attempt to detect what type of variable it is at runtime, and can also do conversion during runtime – for an instance converting an integer or floating point value into a String to concatenate the values. But perhaps you wanted to add two integers together, one being a set of characters representing an integer value in a string. The problem with this is you would have to specify how you want the values added together – whether through addition or concatenation. An example of this is below:

var myNumber = “1”; var myNumber2 = 3; alert(myNumber + myNumber2);

This will likely display an alert box that says 13, when in actuality, you may have wanted it to be 4 – through addition.

An example of a strongly typed language is Java, because you must define each variable and function return type before using them. An example of this is below:

public void Constructor {     System.out.println(doSomething); } private int doSomething {     private int myNumber = 1; return (myNumber + 2); }

This program prints out the value of 3 in the command prompt. You can see how the Constructor was defined to not have a return value, with “void”, and how doSomething does have a return value of type int, or integer.

Struct in Procedural vs. Class in OOP
A structure (struct) is a compound data type that contains different members of different types, accessed by their names, whereas a class is a reference type that is used to define object templates. In a sense, struct and class are very similar. A structure can be seen as a simple implementation of the object paradigm from OOP. A struct is like a class, except it doesn’t have default access because a class has a default access of private, while struct has a default access of public.

A value of a structure-object is a tuple of values of each member of the object. In C++, there is legacy support for older C functions with the struct. A struct can also have constructors, and in some cases must use them. Structures also allow Operator Overloading.

The following struct returns 4:3,

MyStruct i = new MyStruct; i.I = 3; MyStruct j = i; i.I = 4; Console.WriteLine("{0},{1}", i.I, j.I);

Fundamental Structure of OOP
The object-oriented paradigm uses abstraction in the form of either 1) classes and their execution instances called objects, or 2) prototype objects – to create models based on real world objects and their environmental relationships. An object-oriented application uses a collection of objects that communicate by passing messages between one another, which is how the program performs computations. Objects are capable of sending and receiving messages, and processing data. Objects can request that other objects perform actions, by sending messages with arguments, in addition to receiving messages with arguments, in order to perform actions themselves.

The purpose of OOP is to increase flexibility and maintainability. Programs created using an object-oriented language are independently modular, reusable, easier to develop, and simpler to understand. With OOP, you can also encapsulate data, which gives you the ability to hide the details of internal operations within an object from the outside world by using the private namespace. Each object has its own state, which consists of its memory and the state of objects it communicates with.

A class in OOP simply groups similar objects together. Even basic data types such as integers, floats, Booleans, lists, and dictionaries are all classes in object-oriented programming. Their instances could include objects with the data values of 100, 4.0, True, [‘Hello’, ‘World’], and {‘Subjects’:[‘Biology’, ‘Chemistry’]}. Classes aren’t limited to simple data types – they can define complex data types that you define, such as the class of TCP_IP_Com_Channel, which may include a varying amount of data over time that is transmitted between another instance of such a class on another computer, to establish communication over the Internet. There could even be multiple instances of such a class on the same computer, such as multiple instances of an application that uses the class running at the same time. Classes with similar purposes may vary in their properties between different applications.

Encapsulation
Encapsulation in Object-Oriented Programming is the ability of an object to hide data and methods from the outside world, reducing access to internal data. This allows the user of an object to view it like a black box that only provides the services that it needs. OOP allows hiding instance variables and methods, and as long as the services provided by the object remain the same, any other object’s code that uses the object’s services can remain the same without having to be modified.

Encapsulation, or information hiding, can be measured with either tight or loose coupling, which is the degree to which a module, or class, depends on other classes. This is also relative to what information the module’s class shares or hides with other objects. A well-designed OOP module should be loosely coupled from other objects, which means that it has a low dependence on other classes, or that the understanding of one class should not require the understanding of another. With a decoupled class, a change in a module will not require changes in other modules.

An example of encapsulation is a Car and it’s Driver, as such:

private class Car {                             private class Driver { public void move {                              public void goSomewhere { this.engine;                                    Car.move; }                                                 }      private void engine  {                       } // Code to make the engine go! } }

Inheritance
In Object-Oriented Programming, multiple classes can share the same characteristics using inheritance. With this trait, classes can inherit commonly used state and behaviors from other classes. Additionally, classes can still have certain properties that make them unique. This allows data reuse through hierarchical relationships.

Classes in Java occur in inheritance hierarchies. An example of this is to specialize the Animal class, which has functions such as the ability to move, eat, and die – which are inherited by the Fish class. The Fish class is unique, because it has the ability to swim in water – which is a specific trait or customization of the move function from the Animal class. A Goldfish class would inherit the swim class from the Fish class, just as the Salmon class would, and this would make the Animal class a superclass. However, the Goldfish class would have specific traits, such as the specific behavior that it moves in, and its appearance such as color and size, which would be completely different than the Salmon class.

In the following Python program, both SquareSumComputer and CubeSumComputer inherit SumComputer’s properties:

class SumComputer(object): def __init__(self, a, b): self.a = a         self.b = b      def transform(self, x): raise NotImplementedError def inputs(self): return range(self.a, self.b)     def compute(self): return sum(self.transform(value) for value in self.inputs) class SquareSumComputer(SumComputer): def transform(self, x): return x * x class CubeSumComputer(SumComputer): def transform(self, x): return x * x * x

Polymorphism
In computer programming, polymorphism is the provision of a single interface to entities of different types, allowing the generality of data. A polymorphic type is a type that allows its operations to be applied to the values of some other type or types.

There is ad hoc polymorphism, parametric polymorphism, and subtyping. Ad hoc polymorphism is when a function has different uses based on a limited range of types and combinations. Parametric polymorphism is when code is developed without reference to any specific type, which allows it to be used with any number of new types. Subtyping, or inclusion polymorphism, is when a name denotes instances of a group of classes related to come common superclass. There is also the interaction between parametric polymorphism and subtyping, which leads to variance and bounded quantification. In the following Pascal program, the function is able to add either two numbers, or concatenate two strings, in the same function:

program Adhoc; function Add(x, y : Integer) : Integer; begin Add := x + y end; function Add(s, t : String) : String; begin Add := Concat(s, t) end; begin Writeln(Add(1, 2));                  (* Prints "3"             *) Writeln(Add('Hello, ', 'World!'));   (* Prints "Hello, World!" *) end.

Pre-Procedural vs. Imperative

 * A quick contrast with pre-procedural paradigm - imperative.

Structure

 * Lacks structure - no subroutines.

Spaghetti Logic

 * "go-to" dilemma.

Example

 * An example of OOP vs. Procedural would be good here.

Parsing - Syntax Vs. Semantics
Syntax - A set of rules to be followed


 * The arrangement of words/symbols in the structure

Semantics - The meaning of the text


 * The logic concerned with its meaning in the structure

A Lexical Analyzer in Java
What is a token


 * Tokenization: mapping keywords to numeric value

Source code for Java based tokenizer written in class


 * Breaking it into functions and discussing each purpose


 * Adding a header and foot from class definition to make complete Parser.java class

= Week 11 - Parsing: implementing a language - a recursive descent parser in Java = Content authors (Group #5) Bridget Franciscovich and Aashirya Kaushik

Outline by Aashirya Kaushik
 * What is a Parser
 * Types of Parsers: Top-Down vs Bottom-Up
 * Structure of a Parser
 * Parse Tree
 * Grammar in Parsing
 * A Recursive Descent parser: definition
 * Implementing SQRL
 * BNF Grammar for SQRL
 * Source code for SQRL written in class (use week11.zip on web page as source).
 * break into functions and discuss each purpose
 * group some of the one line functions into one chunk
 * some examples of SQRL in action

What is a Parser
Parsing is the process of analyzing a string of symbols, either in natural language or in computer languages, according to the rules of a formal grammar.
 * Top-Down parsers can be slowers due to the recursive descent but they are easier to understand and create. They read from left to right and expands upon the leftmost entry first; Tokens are consumed from left to right.
 * Bottom-Up parsers are faster without recursion, harder to understand, and more popular because of the benefits. come from the concept of a parse tree where the most details come from the bottom and larger structures composed from them are in successively higher layers until at the top or "root" of the tree a single unit describes the entire input stream.

Structure of a Parser

 * Parse Tree or parsing tree or derivation tree or concrete syntax tree is an ordered, rooted tree that represents the syntactic structure of a string according to some context-free grammar.

Constituency-Based Parse Tree

 * The constituency-based parse trees of constituency grammars (= phrase structure grammars) distinguish between terminal and non-terminal nodes. The interior nodes are labeled by non-terminal categories of the grammar, while the leaf nodes are labeled by terminal categories. The parse tree is the entire structure, starting from S and ending in each of the leaf nodes (John, hit, the, ball). The following abbreviations are used in the tree:
 * S for sentence, the top-level structure in this example:
 * NP for noun phrase. The first (leftmost) NP, a single noun "John", serves as the subject of the sentence. The second one is the object of the sentence.
 * VP for verb phrase, which serves as the predicate
 * V for verb. In this case, it's a transitive verb hit.
 * D for determiner, in this instance the definite article "the"
 * N for noun

Dependency-Based Parse Tree

 * The dependency-based parse trees of dependency grammars see all nodes as terminal, which means they do not acknowledge the distinction between terminal and non-terminal categories. This parse tree lacks the phrasal categories (S, VP, and NP) seen in the constituency-based counterpart above. Like the constituency-based tree, the constituent structure is acknowledged. Any complete sub-tree of the tree is a constituent. Thus this dependency-based parse tree acknowledges the subject noun John and the object noun phrase the ball as constituents just like the constituency-based parse tree does.

Recursive Descent Parser
A recursive descent parser is a kind of top-down parser built from a set of mutually recursive procedures (or a non-recursive equivalent) where each such procedure usually implements one of the productions of the grammar. Thus the structure of the resulting program closely mirrors that of the grammar it recognizes.

Grammar in Parsing
Grammars are defined by a set of productions. Productions use two kinds of symbols, terminals and nonterminals. Terminals are also called tokens: they are the symbols that the scanner recognizes and provides to the parser. A nonterminal represents some sequence of tokens in the string that is being parsed. A production has a left-hand-side, which is always a nonterminal. A grammar has a start symbol, usually a nonterminal. A legal string as defined by the grammar is anything that can be generated from the start symbol using productions.

Implementing SQRL
< SQRL> ::=. ::=   ::=   ::= load ::= print ::= input ::= if   ::= = ::= +  ::= -   ::= *   ::= /   ::=   ::= = =  //Note that this is a double equals ::= >    ::=  <    ::=   ::=   ::= |    ::=   ::= | | |    :: = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9   ::= a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z   ::=. | _
 * BNF Grammar for SQRL


 * Source code for SQRL written in class
 * The Parse function is the only public function and it is the constructor.

public Parse {       line = ""; scan = new Scanner(System.in); vars = new int[26]; for (int i = 0; i < 26; i++) vars[i] = 0; }


 * The run function is the entry point into the Parse and therefore codes <SQRL. ::=

public void run throws IOException {       String token;

System.out.println("Welcome to SQRL...");

token = getToken; parseCode(token);                 // ::= }


 * The parseCode function parses token for and therefore codes ::=

private void parseCode(String token) throws IOException {       do { parseStmt(token);             // ::= <stmt | token = getToken; } while (!token.equals(".")); }


 * parseStmt parses the token for each of the statements, load, print, input, if, else, repeat, and variables.

private void parseStmt(String token) throws IOException {       int val; String str;

if (token.equals("load")) {           token = getToken; str = parseString(token);

// interpreter excution part line = loadPgm(str) + line; }       else if (token.equals("print")) {           token = getToken; if (token.charAt(0) == '"')           {                str = parseString(token);

// interpreter execution part System.out.println(str); }           else {               val = parseExpr(token);

// interpreter executin part System.out.println(val); }       }        else if (token.equals("input")) {           token = getToken; val = parseVar(token);

// interpreter excutution part System.out.print("? "); val = scan.nextInt; storeVar(token, val); }       else if (token.equals("if")) {       }        else if (isVar(token)) {       }        else reportError(token); }


 * loadPgm loads a program from a file.

private String loadPgm(String name) throws IOException {       String buffer = ""; File file = new File(name); Scanner fileScan = new Scanner(file);

while (fileScan.hasNextLine) buffer += fileScan.nextLine + "\n";

return buffer; }


 * parseExpr parses token for the different expressions, +, -, *, and /.

private int parseExpr(String token) {       int val; String opToken;

val = parseVal(token); opToken = getToken;

switch (opToken.charAt(0)) {           case '+': token = getToken;       // ::= + val = val + parseVal(token); break; case '-': case '*': case '/': default: line = opToken + line; }       return val; }


 * parseVal parses for as seen in the grammar and returns its value.

private int parseVal(String token) {       if (isNumeric(token)) return Integer.parseInt(token); else return parseVar(token);

//if (isVar(token)) //   return parseVar(token); //       // reportError(token); //       //return -1;  // wont compile without this }


 * parseVar parses a token for and returns its value.

private int parseVar(String token) {       if (!isVar(token)) reportError(token);

return vars[(int)token.charAt(0) - 97]; }

// parse token to see if it's a variable private boolean isVar(String token) {       return token.length == 1 && isAlpha(token.charAt(0)); }


 * storeVar stores thevariable in vars array

private void storeVar(String token, int val) {       vars[(int)token.charAt(0) - 97] = val; }


 * isNumeric is a boolean function that returns true if a token is.

private boolean isNumeric(String token) {       for (int i=0; i<token.length; i++) if (!isDigit(token.charAt(i))) return false;

return true; }


 * isDigit is a boolean function that returns true if a token is a number.

private boolean isDigit(char ch) {       return ((int)ch) >= 48 && ((int) ch) <= 57; }


 * isAlpha is a boolean fucntion that returns true if a token is an alphabetic character.

private boolean isAlpha(char ch) {       return ((int)ch) >= 97 && ((int)ch) <= 122; }


 * parseString skips the lexical analyzer getToken and parses for.

private String parseString(String token) {       int i;        String str="";

// grab string between quotes if(token.charAt(0) != '"')           reportError(token);

for (i=0; i<line.length; i++) if (isNewLine(line.charAt(i))) reportError(token); else if (line.charAt(i) == '"')                break;

if (i == line.length) reportError(token);

str = line.substring(0,i); line = line.substring(i+1);

return str; }


 * isNewLine is a boolean function that returns true if it is a new line.

private boolean isNewLine(char ch) {       switch (ch) {           case '\n': case '\r': return true; default: return false; }   }


 * isBlank is a boolean function that returns true if it is a blank space.

private boolean isBlank(char ch) {       switch (ch) {           case ' ': case '\t': return true; default: return isNewLine(ch); }   }


 * isDelim is a boolean function that returns true if the token is a deliminter (. '' + - * / > < =).

private boolean isDelim(char ch) {       switch (ch) {           case '.': case '"':           case '+': case '-':            case '*': case '/':            case '>': case '<': case '=':                return true;            default:                return isBlank(ch);        }    }


 * skipLeadingBlanks uses isBlank to skip and blank tokens.

private String skipLeadingBlanks(String buffer) {       int i;        for (i=0; i<buffer.length; i++) if (!isBlank(buffer.charAt(i))) break; return buffer.substring(i); }


 * getToken is the tokenizer for the parser.

private String getToken {       int i;        String token;

line = skipLeadingBlanks(line);

while (line.length == 0) {           line = scan.nextLine; line = skipLeadingBlanks(line); }

// grab out actual token for (i=0; i<line.length; i++) if (isDelim(line.charAt(i))) {               if (i==0) i++; token = line.substring(0,i); line = line.substring(i);

return token; }       // entire line is token token = line; line = ""; return token; }


 * reportError reports any syntax errors.

private void reportError(String token) {       line += "\n"; line = line.substring(0, line.indexOf("\n"));

System.out.println("ERROR: " + token + line); for (int i=0; i < 7+token.length; i++) System.out.print(" "); System.out.println("^");

System.exit(-1); }


 * Some examples of SQRL in action

The repeat function
a = 1 b = 1 repeat a to 5 by b repeat b to a by 1 print b + 0

This prints out: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

This is a modulus function that will ask the user using the input function the dividend and divisor, it will then print the modulus of the input.
input dividend input divisor

mod = dividend / divisor mod2 = mod * divisor

if dividend > divisor print mod else print 0

if dividend < divisor print dividend else print mod2 + 0

start = 1 input fact

count = 1 repeat start to num by count if start > 1 fact = fact * start

print fact + 0

= Week 12 - Grammers: Chomskys Hierarchy & Regular Expressions = Content authors (Group #3/4) Raghava Adusumilli and Arjun Padaliya

Outline by Arjun Padaliya
 * What is Chomskys Normal Form?
 * Rules for any context free grammar to be in Chomskys Normal Form.
 * Different classes of grammar and languages introduced by Chomsky.
 * Type 0: Recursively enumerable grammars (give example)
 * Type 1: Context-sensitive grammars (give example)
 * Type 2: Context-free grammars (give example)
 * Type 3: Regular grammars (give example)
 * BNF versus notational form
 * discuss the two ways we've represented them
 * i.e. S -> A  vs    ::=
 * Give examples from class (i.e. a^n b^n)
 * Regular Expression Syntax
 * Character classes ([0-9], [a-z], ...)
 * Meta-characters (., ?, *, \n, \t, ...)
 * Boolean "or"
 * Anchors
 * Iteration
 * Grouping (parentheses)

What is Chomskys Normal Form?
A useful form for dealing with context free grammars is the Chomksy normal form. This is a form of grammar, which helps in writing a CFG and, useful for understanding CFGs and for proving things about them. Every grammar in Chomsky normal form is context-free, and conversely, every context-free grammar can be transformed into an equivalent one which is in Chomsky normal form and has a size no larger than the square of the original grammar's size.

Rules for any context free grammar to be in Chomskys Normal Form.
A context free grammar is in Chomskys Normal Form if the productions are in following forms. A → a A → BC S->ε where A, B, and C are non-terminals and a is terminal. S is start symbol.

Different classes of grammar and languages introduced by Chomsky.
Most famous classification of grammars and languages introduced by Noam Chomsky is divided into four classes:

The hierarchy in the classification of grammar is such that it goes from least specific to more specific.

Type 0: Recursively enumerable grammars
Type 0 (unrestricted grammars) include all formal grammars. They generate all the languages that can be recognized by a Turing Machine. These languages are also known as the recursively enumerable languages. Type 0 grammars are too general to describe the syntax of programming languages and natural languages. The rules for the type 0 grammar are: α->β here α and β are the strings of terminals and non-terminals.

Type 1: Context-sensitive grammars
Type-1 grammars generate the context-sensitive languages. The languages described by these grammars are exactly all languages that can be recognized by a linear bounded automaton. The rules for type 1 grammar are: α A β → α γ β here A is non-terminal and α,β and γ strings of terminals and non-terminals.

Example: * AB → CDB * ABcd → abCDBcd

Type 2: Context-free grammars
Type-2 grammars generate the context-free languages. These languages are exactly all languages that can be recognized by a non-deterministic pushdown automaton. Context-free languages are the theoretical basis for the syntax of most programming languages. The rules for type 2 grammar are: A → γ here A is non-terminal and γ strings of terminals and non-terminals.

Example: * A → aBc

Type 3: Regular grammars
Type-3 grammars generate the regular languages. Such a grammar restricts its rules to a single non-terminal on the left-hand side and a right-hand side consisting of a single terminal,possibly followed (or preceded,but not both in the same grammar) by a single non-terminal.

Example: * A → abc * A → abcB

Regular Expression Syntax
A regular expression (sometimes called a rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching. Regular expressions are a generalized way to match patterns with sequences of characters. It is used in every programming language like C++, Java and Python.

Example: regular expression of email address ^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$

The above regular expression can be used for checking if a given set of characters is an email address or not.

Character Classes
A character class defines a set of characters, any one of which can occur in an input string for a match to succeed. There are different type within the character classes. A positive character group specifies a list of characters, any one of which may appear in an input string for a match to occur. This list of characters may be specified individually, as a range, or both. The syntax for specifying a list of individual characters is as follows: [character_group] where 'character_group' is a list of the individual characters that can appear in the input string for a match to succeed. Example of character group * [Pp]ython Match "Python" or "python" * rub[ye] Match "ruby" or "rube" * [aeiou] Match any one lowercase vowel
 * Positive Character Group

Another way is to do by giving some kind of range. The syntax for specifying a range of characters is as follows: [firstCharacter-lastCharacter] where 'firstCharacter' is the character that begins the range and 'lastCharacter' is the character that ends the range, and both are seperated by - (hyphen). Example for character range * [0-9] Match any digit; same as [0123456789] * [a-z] Match any lowercase ASCII letter * [a-zA-Z0-9] Match any of the above

A negative character group specifies a list of characters that must not appear in an input string for a match to occur. Same as positive group, the list of characters may be specified individually, as a range, or both. The syntax for specifying a list of individual characters is as follows: [^character_group] where character_group is a list of the individual characters that cannot appear in the input string for a match to succeed.
 * Negative Character Group

Example for negative character group * [^aeiou] Match anything other than a lowercase vowel

Another way of using the negative character group is using the range of characters. The syntax for specifying a range of characters is as follows: [^firstCharacter-lastCharacter] where range is the list of characters that should not appear in input string in order to succeed.

Example for negative character group with range [^0-9] Match anything other than a digit

Meta Characters
Metacharacters are the building blocks of regular expressions. Characters in RegEx are understood to be either a metacharacter with a special meaning or a regular character with a literal meaning. The following are some common RegEx metacharacters and examples of what they would match or not match in RegEx.

= Week 13 (& 12) - Grammers: Context Sensitive Grammars & Table driven parsing = Content authors (Group #1) Illya Kovarik and Sharmila Pankaja

Outline by Sharmila Pankaja
 * Context Sensitive Grammar Formal Definition.
 * Properties of context-sensitive languages.
 * Compare CSG to Context Free Grammars (CFG) with respect to programming languages
 * Show and expand example: a^n b^n c^n done on board
 * First show a^n and its grammar (Regular) and a^n b^n and its grammar (CFG)
 * Give the solution of the class: S -> abc S-> aSBc cB -> Bc bB -> bb
 * Explain Kuroda normal form and how it impacts that solution
 * List of parser generator for context sensitive languages

Context Sensitive Grammar Formal Definition
Is a specific type of formal grammar where a set of production rules describe all possible string combinations in a language. The production rules are systematic replacements which do not depend on the context. The term might seem misleading, implying that the grammar is free of or has no context. It means that the language is context invariant, or simply not dependent on any context in particular. Any given contextual situation does not change the CFG rules to be applied.

Properties of context-sensitive languages
The memory of a programming language is limited. The grammar cannot remember the presence of a construct over an arbitrarily long input. Since these grammars are not dependent on a context, they can be mapped unambiguously to exact meaning by using the production rules of the grammar. In other words, the task can be done by machine and this process is an element of the compiler we have just discussed. It means all of the language's production rules have a single non-terminal on its left hand side.

Compare CSG to Context Free Grammars (CFG) with respect to programming languages
Write more here

Show and expand example: a^n b^n c^n done on board
Write more here

First show a^n and its grammar (Regular) and a^n b^n and its grammar (CFG)
Write more here

Give the solution of the class: S -> abc S-> aSBc cB -> Bc bB -> bb
Write more here

Explain Kuroda normal form and how it impacts that solution
Write more here

List of parser generator for context sensitive languages
Write more here

= Week 14/15 - An overview of lex and yacc = Content authors Mike Jonas

Outline by Mike Jonas
 * add item 1
 * add item 2