CMSC 403 Final Exam
Construct a list using cons
(cons "abc" (cons 7 (cons (cons 9 (cons 10 ())) ()))) builds ("abc" 7 (9 10))
Be able to implement a function which returns a function as data
(define (adder n) (lambda (x) (+ x n)
Implementation for If-else-if in lisp
(if(Condition) (true branch) ( -if (if (condition) (true branch) -else if (false branch) -else ))
REPL loop
- (read) Reads in user input - (eval) Evaluate input - (print) Print evaluation - (loop) Wait for next input It is an interactive computer programming environment that takes user input, executes them, and returns result to user.
Understand the difference between free format and fixed format
Free format language: One in which format has no effect on program structure other than satisfying the principle of longest substring. Fixed format language: One in which specific tokens must occur in pre-specified locations on the page
Memory Management used by Common Lisp:
Garbage Collection
Scope hole:
Global variable has a scope hole in a block containing a local declaration with the same name.
Be able to determine if a given grammar has a finite or infinite number of legal derivations
Grammars are infinite when there is at least one recursive or iterative in the case of ENBF's rule.
Difference between implicit and explicit conversion
Implicit conversion is inserted by the translator. Explicit conversion has to do with conversion directives being written into the code.
Be able to define a Just in Time Compiler
In Just-In-Time, java source code is compiled into .class bytecode at compile time, then in run-time the JIT compiler compiles the bytecode of that method into native machine code. JIT is part of JVM. It compiles bytecodes to machine code at run time.
Different simple types discussed in lecture
- Predefined type: Types supplied within a language - Ordinal type: Type that exhibits a discrete order on the set of values (Integers, comparison operators, successor, and predecessor operations) - Enumerated type: Sets whose elements are named and listed explicitly - Subrange: Contiguous subsets of simple types specified by giving least and greatest elements.
Know the four types of function parameters and how to utilize them in a function's parameter list.
- Required - The default parameters - Optional - To make parameters optional, place them after the &optional symbol. All parameters which come before the &optional symbol will be required parameters. - Rest - Any arguments remaining after all other parameters have been assigned values are placed into a list. The list becomes the value of the rest parameter. - Key - Allows the caller to specify which values go with which parameters
Difference between simple and complex types
- Simple: Have no other structure than their inherent arithmetic or sequential structure Complex: Types like arrays, objects
Define the symbol table, environment, and memory in the context of binding
- The compiler relies on the symbol table which is used to keep track of all the names in a statically scoped program. - The environment maintains the binding of these names to locations - To allow for arbitrary allocation and deallocation, the environment must have an area in memory from which locations can be allocated. - Memory binds memory locations to addresses
Know that functions are first class data values / functions as data
- They can be treated as data, given as parameters, and returned as the return value of another function.
Know what an activation record is and what it is comprised of
It is a data structure containing the important state information for a particular instance of a function call. It is comprised of... BRALT - Book-keeping information - Return Values - Arguments - Local Variables - Temporaries
Know about the concept of Monitors in Java
Monitors are an abstract data type that run only one thread at a time through it. Resolves critical sections.
Understand how Python supports multiple assignment and know sequence packing and unpacking
Multiple assignment - x = "Dahlberg is cool" - y = "mainframe is cool" - x, y = y, x - print (x) # mainframe is cool - print (y) # Dahlberg is cool Sequence packing and unpacking - x, y, z = 1, 2, 3 - w = x, y, z - print (w) # (1, 2, 3)
In terms of space complexity, explain why stack allocation is better than static allocation
Natural nesting within subroutine calls make it easier to allocate space.
Does casting have a purpose in a dynamically typed language?
No, because data types are managed dynamically, so there would be no point.
What type does Python have?
Python only has object types
To combine parameter types, they must be defined in a specific ordering:
Required -> Optional -> Rest -> Key
Type equivalence
Rules for determining if two types are the same
Difference between statically typed language and a dynamically typed language
Static - Types are determined from the text of the program and checked by the translator. Dynamic - Type information is maintained and checked at runtime
Referential Transparency and its side effects
The property where the value of any function depends only on the values of its arguments. Side effects - Change in the value of a variable that persist beyond the local scope.
Define the von Neumann bottleneck and understand how it is related to the Processor-Memory performance gap
The von Neumann bottleneck is the idea that computer system throughput is limited due to the relative ability of processors compared to top rates of data transfer. According to this description of computer architecture, a processor is idle for a certain amount of time while memory is accessed. The CPU executes instructions much faster than memory can give them to the CPU.
What it means for a grammar to be ambiguous
A grammar is ambiguous when a single statement can have multiple grammatically valid derivations
Dangling Reference
A reference to an object that no longer exists. They arise during object destruction, in the event when an object that has an incoming reference is deleted/deallocated, without the modification of the value of the pointer, so that the pointer still points to the memory location of the deleted/deallocated memory.
Know the syntax for inheritance in Python
class Subclass (SuperClass1, SuperClass2, ...):
Two categories of binding
Dynamic and Static.
Know the described access modifiers
x = Public - Accessible from outside the class through an object of the class _y = Protected - Accessible from the package and are also available to its sub-classes __z = Private - Can only be accessed inside the class
Be able to implement a function which takes a function as a parameter
(defun bigDome (f x) (funcall f x x)
Know how to define a function in Common Lisp
(defun name (parameters) "Optional Documentation String" (body))
Know what an Anonymous Inner Class is in Java
A class without a name and which only a single object is created
Be able to define and describe a lexical analyzer (i.e. a definition, not a program)
A lexical analyzer is a pattern matcher for character strings. It identifies substrings of the source program that belong together - lexemes
Functional Programming
A programming paradigm which treats computation as the evaluation of mathematical functions.
Describe a Java stream
It is basically taking a collection of objects and applying intermediate functions on said collection and then finishing with a terminal operation. Does not modify the underlying collection; it only returns a new one
Be able to define and describe a recursive descent parser
It turns Nonterminals into a group of mutually recursive procedures based on the right-hand sides of the BNFs. It turns non-terminals into functions.
Overload Resolution:
Process of choosing a unique function among many with the same name. The symbol table can determine the appropriate function based on number and type of parameters.
TRUE OR FALSE there is no single widely accepted way of formally defining dynamic semantics
True
Name equivalence
Two types are the same only if they have the same name
Know the two types of programming language abstractions and the three levels of programming language abstractions
Two types of programming language abstractions Data abstraction - Simplifies the behavior and attributes of data for humans Control abstraction - Simplifies properties of the transfer of control (Assembly language and looping) Three levels of programming language abstractions Basic abstractions - Collect the most localized machine information Structured abstractions - Collect intermediate information about the structure of a program Unit abstractions - Collect large scale information in a program
Special Operator
Type of atomic operator defined to behave in ways a function cannot. It is necessary because...
Be able to define the principle of longest substring
Use the principle of longest substring to eliminate confusion - This is the process of collecting the longest possible string of nonblank characters to determine lexemes - Ex: The longest possible string of nonblank characters is collected into a lexeme, so doif and x12 are identifiers
Three types of memory management
- Automatic Reference Counting: Determines objects references at compile time. Injects allocation and deallocation instructions into the compiled program. Allows for the efficiency of manually managed memory with the security of garbage collection. - Manual Memory Management: Usage of manual instructions by the programmer to identify and deallocate unused objects, and garbage. - Garbage Collection: Process of automatically reclaiming garbage. Garbage collection offers increased reliability, and less developer time chasing memory management errors.
2 reasons a heap would be needed for storage allocation
- Don't know the amount of data needed at runtime - Need to allocate a lot of data
Know the computational paradigms discussed in class
- Imperative - Sequential instruction execution, variables representing memory locations. - Functional - Treats programs as functions, treats functions as data. - Logic - Based on formal symbolic logic. - Scripting - Coordination or concatenation of components from some surrounding context. - Object Oriented - Allows programmers to write reusable code that mimics the behavior of objects in the real world.
Know how to add variables and functions to an object instance or an object class "on the fly"
- setattr (variable, name, value) - call class name with needed class instance like Dog.type = 'sometype' after class declaration. This will modify all Dog objects - can add instance variables to particular instances of object in a similar manner.
Two benefits of tail recursion relative to standard recursion
1. Does not incur stack depth issues involved with regular recursion. 2. Don't need to take the time to create new stack frames So it is a speed & memory boost
Understand the main advantage and disadvantage of reflection
Advantages: Allows programs to be more dynamic by subverting the static typing system. Allows for objects to be modified at runtime regardless of access modifiers. Disadvantages: People can backdoor your stuff. Subverts static typing. Makes programs unsafe.
Know that streams are computed lazily
Allows for optimization
Be able to define attribute grammar
An attribute grammar is a context-free grammar with the following additions: - Each nonterminal is associated with a set of attributes - Each production has a set of rules that define attributes of the Nonterminals
Know what a functional Interface is in Java
An interface with a single abstract method.
Understand why EBNF grammars are not sufficient in describing syntax
Because EBNFs are context free and in most cases where EBNFs are used you need to use them based on context.
What is binding?
Binding is the process of associating an attribute with a name. It is the association of objects and implementations with names in programming language so that those objects and implementations can be accessed by the names.
Two components of a cons cell
Car - Returns the first element of the given cons cell, the head of our list Cdr - Return the second element of the given cons cell, the rest of our list
Difference between casting & conversion
Casting is interpreting the data type as another, whereas conversion is changing the data type to another.
Know how interrupting a thread works in Java
Causes an interrupted exception. (Request is made to interrupt. You can't actually stop (hence stop being deprecated)).
Know the difference between class variables and instance variables
Class variables are defined within the class construction. They are shared by all instances of the class and will generally have the same value for every instance. Instance variables are owned by instances of the class. For each object or instance of a class, the instance variables are different. Instance variables are defined within methods.
Lexical address
Combination of lexical depth and position. Each name has a lexical address which is composed of a level number and an offset.
Be able to compare and contrast a compiler, an interpreter, and a hybrid implementation system
Compilers and interpreters are similar in the fact that they both translate programs into machine language, so no programming language has a specific implementation. It just so happens that Java leans more towards compilation while python leans more towards interpretation. They are different in that the compilation method has programs translated to machine language before execution, while the interpreted method has programs translated into machine language at runtime. Compilation method usually leads to greater performance than Interpreted method. I should also note that Interpreted languages are slower to execute (10-100x slower than compiled programs). Though, it is easier to implement an interpreter. Additionally, the compilation process has several phases, where the interpretation process is much simpler, though obviously slower as mentioned. The hybrid implementation combines both compiler and interpreter implementations into one. We say that a language is compiled if the translator analyzes it thoroughly and if the intermediate program does not bear a strong resemblance to the source. If it's a hybrid system, so having those hallmarks of compilation, if it runs through does a transformation but also an analysis and can report errors at a time other than when the code is being executed
What it means for a grammar to be context free
Context-free grammar: A formal specification of syntax which consists of a series of grammar rules
Type conversion
Converting from one type to another
Type conversion
Converting from one type to another.
Type Conversion
Converting from one type to another. Includes implicit and explicit conversion. Implicit conversion is conversion inserted by the translator. Explicit conversion is conversion directives written into the code. Also includes widening and narrowing conversion. Widening conversion means that the target data can hold all converted data without data loss. Whereas, narrowing conversion means that the conversion may include a loss of data.
Know the two types of attribute grammar rules discussed in lecture
Copy rules: Specify that one attribute should be a copy of another Semantic functions: Arbitrarily complex functions specified by the language designer - Each semantic function takes an arbitrary number of arguments, and each computes a single result, which must likewise be assigned into an attribute of a symbol in the current production
Know low coupling, high cohesion. What it is and why it's important
Coupling: how related or dependent two classes are toward each other Low Coupling: Different program units aren't highly dependent on each other Cohesion: what the class can do - Low cohesion: a class has a broad focus - High cohesion: a class has a narrow focus
Know about multiple inheritance and the deadly diamond of death
Deadly diamond of death is the generally used term for an ambiguity that arises when two classes B and C inherit from a superclass A, and another class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?
Understand what it means for a streams behavioral parameters to be non-interfering and why this is necessary for parallel execution of streams
Doesn't modify the source
Be able to name and define the language design criteria focus areas
Efficiency - Usually thought of as efficiency of the target code. Is PROGRAMMER EFFICIENCY. How quickly and easily can I read and write in the programming language? - Writability: The quality of a language that enables a programmer to use it to express computation clearly, correctly, concisely, and quickly. - Expressiveness: How easy is it to express complex processes and structures? "{}" block structure in general - Readability: How easy is it to comprehend the computations in a program? - Regularity - Refers to how well features of a language are integrated. Greater regularity implies fewer restrictions on the use of particular constructs - Related to reliability - A language designed with security in mind discourages programming errors and allows errors to be discovered and reported Extensibility - An extensible language is a language that allows the user to add features to it.
Know the four ways software components can be modified for reuse
Extension of the data or operations - Example: Adding new methods to a queue to allow elements to be removed from the rear and added to the front to create a double-ended queue or dequeue. - Example: A window defined on a computer screen that is specified by its four corners extended to display text becoming a text window Redefinition of one or more of the operations - Example: If a square is obtained from a rectangle, an area or perimeter function may be defined to account for the reduced data needed in the computation - Example: A window extended to display text must redefine the display operation in order to display the text as well as the window itself Abstraction - Example: A circle and rectangle object can be combined into an abstract object called a figure, to contain the common features of both, such as position and movement Polymorphism - Extending the types that an operation applies to such as the toString method, that is applicable to any object as long as it has a textual representation
Know the difference between a deep copy and a shallow copy
In short, it depends on what points to what. In a shallow copy, object B points to object A's location in memory. In deep copy, all things in object A's memory location get copied to object B's memory location. Deep copy - Constructs a new compound object and then recursively inserts copies into it of the objects found in the original. Shallow copy - Constructs a new compound object and then (to an extent possible) inserts references into it to the objects found in the original.
Be able to define Java Reflection
Java Reflection is the process of analyzing and modifying all the capabilities of a class at runtime. Reflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc. at runtime. (Java reflection is a feature which allows programmers to examine and modify the runtime behavior of a program). Includes: Properties of a class, including its declaration and contents, members of a class, fields, methods, and constructors, the properties of array's and enumerated types.
Know the most common way of informally defining dynamic semantics
Language reference manual
Be able to name and define the two parser classes discussed in lecture
Left-to-right, Left-most derivation or LL (Also called "Top-down" or "predictive" parsers) - Constructs a parse tree from the root down, predicting at each step which production will be used to expand the current node, based on the next available token of input. - Easier than LR parsers - Can be written by hand or generated automatically Left-to-right, Right-most derivation or LR (Also called "Bottom-up" or "shift reduce" parsers) - They construct a parse tree from the leaves up, recognizing when a collection of leaves or other nodes can be joined together as the children of a single parent - LR parsers are almost always constructed by a parser-generating tool
Define lexis, lexeme, and token
Lexis: Short for Lexical structure (The structure of the terminals in a language) Lexeme: Logical groupings of characters Token: Categories of lexemes
How cons cells are utilized to create a list
List L is a pointer to a cell, with the car storing the first value and cdr storing a pointer to the next cell.
Know what a list and tuple is in Python and be able to describe the similarities and differences between the two.
Lists: Ordered and accessed by index, mutable, able to hold objects of arbitrary type, able to hold objects of different types, dynamically sized. Tuples: Similar to lists but possess some key differences. They are immutable, support sequence packing and unpacking, support access by attribute Similarities: They are both sequence data types that store a collection of items. They can store items of any data type. Differences: Tuples are immutable, lists are mutable. Lists consume more memory compared to Tuples. Tuples have structure while lists have order.
Type constructor
Mechanisms used with a group of basic types to construct more complex types
Type constructors
Mechanisms used with a group of basic types to construct more complex types - Cartesian product - Union - Arrays - Pointers - Subset
Garbage
Memory that has been allocated in the environment but that has become inaccessible to the program. Can occur in C by failing to call free before reassigning a pointer variable.
Does casting have a purpose in a dynamically typed language?
No, because the data types are managed dynamically.
Can JAVA lambda expressions create functions as data?
No.
Are Python 2 and Python 3 interchangeable?
No. Python 2 is depreciated and is significantly different from Python 3. Solutions which work in Python 2 will most likely not work in Python 3.
Know how to add grammar rules to a given EBNF grammar
Only thing about EBNFs is that recursive rules are replaced with iterative versions such that when doing leftmost derivations you don't end up creating an infinite loop.
Be able to name the three major classes of formal notation
Operational Semantics - Describing the meaning of a program by executing its statements on a machine either simulated or actual. The change in the state of the machine define the meaning of the statement. Axiomatic Semantics - Based on formal logic - Original purpose: formal program verification - Axioms are defined for all statements in the language (to allow transformations of expressions to other expressions) - Expressions are called assertions Denotational Semantics - Based on recursive function theory - Formal mathematical methods: precise, but are also complex and abstract - Requires study to understand - To define a denotational specification, you define a function mapping language entities onto math objects. Transformation of entities must be explained through math manipulations. Due to its complexity, it isn't commonly used outside of academia.
Type Constructor:
Operations on sets, but those sets are going to be simple types. Basically, combining simple types together in a way that we can get more complex types.
Cons cell
Pair of values
Be able to define Python's typing and binding paradigm (both what it is and how it works)
Python is dynamically typed and dynamically bound. it dynamically typed because it does not have data type defined in the variable so no type checking during compile time. type checking is looking at two data are compatible the program is doing operation. if it is incompatible then python will throw an exception. Dynamic bound means that all method call is looked up at runtime by name
Python is pass by _____ and _____ scoped?
Python is pass-by-value and statically scoped
Does Python have a traditional for Loop?
Python lacks a traditional for loop
Know why Python is able to concisely implement functional constructs.
Python treats functions as data
Know the relationship between left recursive grammar rules and recursive descent parsers
Recursive descent parser: A LL parser whose functions correspond one-to-one, to the Nonterminals (i.e. the right-hand sides of productions) of the grammar - Terminals are matched directly with input tokens as constructed by a scanner - Nonterminals are interpreted as calls to the procedures corresponding to the terminals Left recursive grammar rules: Curly brackets in EBNF represent left recursive removal by the use of a loop
Be able to define single-symbol lookahead and predictive parser
Single symbol-symbol lookahead: Using a single token to direct an LL parse Predictive parsers are the same as LL parsers, which construct a parse tree from the root down, predicting at each step which production will be used to expand the current node, based on the next available token of input.
Understand slice and range: how they work, how they are similar, how they are different.
Slice is used to slice a given sequence (string, bytes, tuple, list, or range) or any object which supports sequence protocol. Range generates the immutable sequence of numbers starting from the given start integer to the stop integer. In Python, ranges and slices are very similar § Both conform to the start, stop, and step design pattern Subtle differences between the two § Range objects are iterable and slice objects are not § Slices can be used as indices, ranges can not § You can slice a range, but you cannot range a slide
Know the difference between static semantics and dynamic semantics
Static Semantics - Nothing to do with meaning - Indirectly related to the meaning of programs during execution - Compile time (data typing, etc) Dynamic Semantics - How and when various constructs of a language should produce behavior (What the language constructs actually do) - Actual meaning of the language
Difference between static and dynamic binding
Static binding - occurs prior to execution. Can be bound during translation, during linking the program with libraries, or during loading of the program. Dynamic Binding -occurs during execution. Can be bound at different times during execution, such as entry or exit from a procedure or from the program.
Define the three principal storage allocation mechanisms
Static objects - Given an absolute address retained throughout the programs execution Stack objects - Allocated and deallocated in LIFO order, usually in conjunction to subroutine calls and returns. Heap objects - May be allocated and deallocated at arbitrary times.
Know why stop and suspend are deprecated
Suspend is deprecated since it is deadlock prone. Stop is deprecated since its considered "unsafe" (unlocks all monitors that it has locked ...).
Know the two parts of syntactic analysis and know why they are two distinct parts
Syntactical analysis portion of a language processor consists of two parts: - Lexical structure à Scanning & Tokenizing - Syntactic structure à Parsing Scanning Phase: The phase in which a translator collects lexemes from the input programs and associates them into tokens Parsing Phase: The phase in which the translator processes the tokens, determining the program's syntactic structure
Be able to define and explain the difference between syntax and semantics
Syntax: The structure of the expressions, statements, and program units Semantics: The meaning of the expressions, statements, and program units
Know the two types of attributes discussed in class
Synthesized attributes: Values are calculated (synthesized) only in productions in which their symbols appears on the left-hand side Inherited attributes: Attributes whose values are calculated when their symbol is on the right-hand side of the current production
Define the von Neumann architecture and how it relates to the Fetch-Decode-Execute cycle
The Von-Neumann Architecture is a concept in which computers are forever hardwired with a small set of operations. - A processing unit that contains an arithmetic logic unit and processor registers - A control unit that contains an instruction register and program counter - Memory that stores data and instructions - External mass storage - Input and output mechanisms
Fetch-Decode-Execute cycle
The instruction cycle (also known as the fetch-decode-execute cycle, or simply the fetch-execute cycle) is the cycle that the central processing unit (CPU) follows from boot-up until the computer has shut down in order to process instructions. It is composed of three main stages: the fetch stage, the decode stage, and the execute stage. - Fetches a program instruction from the main memory - Decodes the instruction, i.e. works out what needs to be done - Executes, i.e. carries out, the instruction
If it is a finite number, be able to determine the number of legal derivations
To determine the number of legal derivations, first generate a string from said language and see what non-terminals are in the final form of the string subsequently taking the rule of products. EX. grammar below 1) sentence à noun-phrase verb-phrase 2) noun-phrase à article noun 3) article à a | and | the 4) noun à girl | competitor | win | dog | comp 5) verb-phrase à verb noun-phrase 6) verb à sees | permits | objects Generating a sentence "a girl sees a dog", we see that the final format is of the form (article noun verb article noun). Article has 3 rules, noun has 5 rules, verb has 3 rules, so if you do the rule of products on this we have the expression 3 x 5 x 3 x 3 x 5 = 675 legal sentences that can be derived from this language.
Be able to define what translation scheme is and describe the scheme we covered in class
Translation scheme: An algorithm that decorates parse trees by invoking the rules of an attribute grammar. - Simplest scheme is one that makes repeated passes over a tree, invoking any semantic function whose arguments have all been defined, and stopping when it completes a pass in which no values change (Such a scheme is said to be oblivious)
Understand the difference between the variable namespace and the function namespace
Variable names are bound to data in one namespace, and function names are bound to another. In instances where we have functions as data, we can't just use that data as a function because it is going to be bound in the wrong namespace.
Be able to define tail recursion
When the recursive step is the last step in any function. So, a function is tail recursive when the last thing a function has to do is the recursive call.
Know how to define an object class
class Mainframe master = None # this is a class variable. (must use self for instance variables) def __init__(self): self.master = "dahlberg" self.dome = "quad"
Know how to do a deep and shallow copy in Python
copy.copy(x) copy.deepcopy(x)
Understand how the synchronize keyword works
keyword is fundamental for programs that use multiple threads. Ordinarily, if you have multiple threads all accessing the same data concurrently, there is risk of a so-called race condition. For example, one thread could see data in an inconsistent or out-of-date state because another thread is in the process of updating it. If the two threads are attempting to perform competing operations on the data, they could even leave it in a corrupt state. Understand how the wait and notify methods work and where they are defined Wait() blocks a thread until another thread calls notify on the same object. Notify - NotifyAll signals any waiting threads to resume
Know the three principles of Object Oriented Programming and be able to describe them
o Encapsulation - Packaging of data with a set of operations that can be performed on the data. Hides internal representation, or state, of an object from the outside. o Inheritance - A new class can be defined to borrow behavior from another class. The new class is called a subclass, and the other (the one being borrowed from) is called a superclass o Polymorphism - Characteristic of allowing an entity such as a variable, function or object to have more than one form based on the different contexts in which it is used. Gives object-oriented systems the flexibility for each object to perform an action just the way that it should be performed for that object.