This document discusses functional objects in Scala. It covers several key points in 3 sentences:
Functional objects are immutable objects without mutable state. They define methods that do not change the object but return a new value. This allows natural and concise notation for methods used as infix operators and method overloading without side effects. The document also discusses defining operators, adding fields, self references, auxiliary constructors, and private fields and methods to implement functional objects in Scala.
The document discusses object-oriented programming (OOP) concepts in C++. It defines key OOP concepts like classes, objects, encapsulation, inheritance and polymorphism. It explains that in OOP, classes encapsulate both data and functions that operate on that data. Classes define public and private sections to control access to members. The document also provides examples to demonstrate class definition, object creation, member functions and destructors.
This document provides an overview of object-oriented programming concepts in C++ including classes, objects, encapsulation, and templates. It introduces the stack data structure and shows how to implement it using structs in C and then classes in C++. It demonstrates how classes allow data and functions to be bundled together through methods and constructors. The document also discusses templates which allow classes to be parameterized for different data types.
C++ classes allow programmers to encapsulate data and functions into user-defined types called classes. A class defines the data attributes and functions that operate on those attributes. Classes support object-oriented programming by allowing objects to be created from a class which store and manipulate data private to the class through public member functions.
Category theory concepts such as objects, arrows, and composition directly map to concepts in Scala. Objects represent types, arrows represent functions between types, and composition represents function composition. Scala examples demonstrate how category theory diagrams commute, with projection functions mapping to tuple accessors. Thinking in terms of interfaces and duality enriches both category theory and programming language concepts. Learning category theory provides a uniform way to reason about programming language structures and properties of data types.
Functions are the building blocks of C++ and are used to reduce program size by calling reusable code in different places. Functions can return values using the return statement. Function prototypes provide interface details like data types and arguments to the compiler. Parameters can be passed by reference, allowing the calling function to modify the original argument. Inline and recursive functions are also discussed. Classes are user-defined data types that contain data members and member functions. Member functions can be defined inside or outside the class.
This document summarizes Kotlin lambda basics and advanced topics:
1. Lambdas allow defining anonymous functions that can be passed as parameters or returned as values. They simplify code by removing the need for anonymous classes.
2. The Kotlin standard library provides many higher-order functions that operate on collections using lambdas, such as filter, map, reduce, and more.
3. Advanced lambda topics include higher-order functions, using lambdas with Java interfaces, closure, and applying lambdas in design patterns like the strategy pattern.
The document discusses arrays in C++ programming, including how to declare and initialize arrays, access array elements using indexes, and provides examples of programs that read user input into arrays, calculate sums of array elements, and print arrays in reverse order. It also explains common array sorting algorithms like selection and bubble sort and provides examples of their implementation.
The document discusses constructors and the this keyword in Java. It explains that constructors initialize objects and can have parameters. The this keyword refers to the current object instance and can be used to call another constructor from within a constructor. Implicit parameters refer to the current object instance from within member methods and constructors when no explicit reference is provided.
The document discusses object-oriented programming (OOP) concepts in C++. It defines key OOP concepts like classes, objects, encapsulation, inheritance and polymorphism. It explains that in OOP, classes encapsulate both data and functions that operate on that data. Classes define public and private sections to control access to members. The document also provides examples to demonstrate class definition, object creation, member functions and destructors.
This document provides an overview of object-oriented programming concepts in C++ including classes, objects, encapsulation, and templates. It introduces the stack data structure and shows how to implement it using structs in C and then classes in C++. It demonstrates how classes allow data and functions to be bundled together through methods and constructors. The document also discusses templates which allow classes to be parameterized for different data types.
C++ classes allow programmers to encapsulate data and functions into user-defined types called classes. A class defines the data attributes and functions that operate on those attributes. Classes support object-oriented programming by allowing objects to be created from a class which store and manipulate data private to the class through public member functions.
Category theory concepts such as objects, arrows, and composition directly map to concepts in Scala. Objects represent types, arrows represent functions between types, and composition represents function composition. Scala examples demonstrate how category theory diagrams commute, with projection functions mapping to tuple accessors. Thinking in terms of interfaces and duality enriches both category theory and programming language concepts. Learning category theory provides a uniform way to reason about programming language structures and properties of data types.
Functions are the building blocks of C++ and are used to reduce program size by calling reusable code in different places. Functions can return values using the return statement. Function prototypes provide interface details like data types and arguments to the compiler. Parameters can be passed by reference, allowing the calling function to modify the original argument. Inline and recursive functions are also discussed. Classes are user-defined data types that contain data members and member functions. Member functions can be defined inside or outside the class.
This document summarizes Kotlin lambda basics and advanced topics:
1. Lambdas allow defining anonymous functions that can be passed as parameters or returned as values. They simplify code by removing the need for anonymous classes.
2. The Kotlin standard library provides many higher-order functions that operate on collections using lambdas, such as filter, map, reduce, and more.
3. Advanced lambda topics include higher-order functions, using lambdas with Java interfaces, closure, and applying lambdas in design patterns like the strategy pattern.
The document discusses arrays in C++ programming, including how to declare and initialize arrays, access array elements using indexes, and provides examples of programs that read user input into arrays, calculate sums of array elements, and print arrays in reverse order. It also explains common array sorting algorithms like selection and bubble sort and provides examples of their implementation.
The document discusses constructors and the this keyword in Java. It explains that constructors initialize objects and can have parameters. The this keyword refers to the current object instance and can be used to call another constructor from within a constructor. Implicit parameters refer to the current object instance from within member methods and constructors when no explicit reference is provided.
Classes allow users to bundle data and functions together. A class defines data members and member functions. Data members store data within each object, while member functions implement behaviors. Classes support access specifiers like public and private to control access to members. Objects are instances of classes that allocate memory for data members. Member functions can access object data members and are called on objects using dot notation. Friend functions allow non-member functions to access private members of classes.
The document discusses object-oriented programming concepts including encapsulation, inheritance, and polymorphism. It provides an example class called Point that demonstrates defining data members and member functions. It then provides a more detailed example of a Set class that implements common set operations like adding/removing elements and computing intersections/unions. The document also discusses constructors and destructors and how they are used to initialize and clean up class objects.
The Ring programming language version 1.4 book - Part 9 of 30Mahmoud Samir Fayed
This document provides documentation on Ring programming language classes, functions, and objects. It includes sections on getting class and method names, checking types, accessing and modifying object attributes and methods, and sharing methods between classes without inheritance. Various functions are described like classes(), isclass(), attributes(), methods(), addattribute(), and setattribute(). Examples are provided to illustrate the usage of each function.
The document discusses classes, objects, and methods in object-oriented programming. It introduces the Dice class as an example, which models the behavior and properties of dice. The Dice class has private member variables to store the number of sides and rolls, and public methods like Roll() and NumSides() to access and manipulate these properties. The document explains concepts like encapsulation, properties, static methods, and the importance of classes and objects in organizing code into reusable components.
The Ring programming language version 1.2 book - Part 22 of 84Mahmoud Samir Fayed
The document provides documentation on Ring programming language functions for working with classes, objects, attributes and methods. It describes functions such as classes(), packageclasses(), isclass(), classname(), objectid(), isobject(), attributes(), methods(), isattribute(), addattribute(), addmethod(), getattribute(), and setattribute(). Examples are given showing how to use each function to get information about classes and objects, check types, add/get/set attributes and methods, etc.
The Ring programming language version 1.5.2 book - Part 32 of 181Mahmoud Samir Fayed
The document provides documentation on Ring programming language functions for working with classes, objects, attributes and methods. It summarizes over 40 functions, including classes() to get class names, isclass() to check if a class exists, packageclasses() to get classes in a package, addattribute() to add attributes to an object, and getattribute()/setattrbute() to get/set attribute values. Examples are given for each function.
The Ring programming language version 1.4.1 book - Part 9 of 31Mahmoud Samir Fayed
This document summarizes reflection and meta-programming functions in the Ring programming language. It describes functions to get information about code at runtime like variable names, functions, classes and more. It also describes functions to check and modify objects, like getting/adding attributes, checking if an attribute exists, and more. These meta-programming capabilities allow Ring programs to introspect and modify their own code and objects at runtime.
Principles of functional progrmming in scalaehsoon
a short outline on necessity of functional programming and principles of functional programming in Scala.
In the article some keyword are used but not explained (to keep the article short and simple), the interested reader can look them up in internet.
This document summarizes advanced JavaScript concepts including:
- Object-oriented inheritance patterns in JavaScript and trends toward avoiding new and emulating private members. Pseudo-classical inheritance is recommended for better performance.
- Exploiting JavaScript's support for functional programming with higher-order functions to allow functions as arguments and return values for more flexible programming.
- Common issues with asynchronous code in JavaScript and how promises can help address callbacks and synchronization.
- Common pitfalls to avoid with arrays, numbers, and typeof in JavaScript.
Slides from my talk at the Junction (Jan 24, 2013)
Single-core performance has hit a ceiling, and building web-scale multi-core applications using imperative programming models is nightmarishly difficult. Parallel programming creates a new set of challenges, best practices and design patterns. Scala is designed to enable building scalable systems, elegantly blending functional and object oriented paradigms into an expressive and concise language, while retaining interoperability with Java. Scala is the fastest growing JVM programming language, being rapidly adopted by leading companies such as Twitter, LinkedIn and FourSquare.
This presentation provides a comprehensive overview of the language, which managed to increase type safety while feeling more dynamic, being more concise and improving readability at the same time. We will see how Scala simplifies real life problems by empowering the developer with powerful functional programming primitives, without giving up on the object oriented paradigm. The overview includes tools for multi-core programming in Scala, the type system, collection framework and domain-specific languages. We’ll explore the power of compile-time meta-programming, which is made possible by the newly released Scala 2.10, and get a glimpse into what to expect from 2.11 in 2014.
We will also see how Scala helps overcome the inherent limitations of Java, such as type erasure, array covariance and boxing overhead.
Multiple examples emphasize how Scala pushes the JVM harder than any other mainstream language through the infinite number of boilerplate busters, increased type safety and productivity boosters from a Java developer’s perspective.
The Ring programming language version 1.9 book - Part 41 of 210Mahmoud Samir Fayed
This document provides summaries of Ring programming functions related to classes and objects. It describes functions for getting class names and checking class definitions, getting classes within packages, and checking class and attribute definitions. It also summarizes functions for working with objects, including getting/setting attributes and methods, checking if an object or attribute exists, and adding attributes and methods to objects. Examples are provided to demonstrate the usage of each function.
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
Scala is a programming language that combines object-oriented and functional programming. It runs on the JVM and is interoperable with Java. Scala is statically typed and concise.
Scala allows modeling of concepts like rational numbers and mutable cells. Classes can implement traits to mix in functionality like logging. Pattern matching makes deconstructing data structures like lists and optional values easy. The Scala library includes collections, functions, and other functional programming constructs.
The Ring programming language version 1.3 book - Part 22 of 88Mahmoud Samir Fayed
The document provides an overview of functional programming concepts in Ring, including pure functions, first-class functions, higher-order functions, and anonymous functions. It defines pure functions as functions that do not change state by copying function parameters rather than modifying original values. It also explains that in Ring, functions are first-class citizens that can be passed as parameters, returned as values, or stored in variables, and demonstrates how to call a function stored in a variable.
This document provides an introduction and overview of inheritance in C#, including:
- Inheritance allows classes to extend existing classes, inheriting members and behavior
- Derived classes can call base class constructors via the base keyword
- The protected keyword controls accessibility for inherited members
- Virtual and override enable dynamic binding and polymorphism by allowing derived classes to override base class methods
- Abstract classes define common interfaces for derived classes to implement
The Ring programming language version 1.5.2 book - Part 37 of 181Mahmoud Samir Fayed
This document discusses using the Ring programming language to create natural language programs based on classes and objects. It provides an example of defining classes to represent the natural language instructions "I want window" and "Window title =". The example shows how objects can execute code for each instruction. The document also discusses changing the Ring keyword "and" to avoid conflicts when parsing natural language statements. In summary, this document demonstrates how Ring allows programmers to build natural language interfaces by defining classes for natural language statements.
Scala is a multi-paradigm programming language that runs on the JVM. It combines object-oriented and functional programming concepts. SBT is the build tool used for Scala projects and allows for incremental compilation. Scala has a uniform approach to collections that emphasizes immutability and uses higher-order
The document discusses various object-oriented programming concepts in C#, including abstraction, encapsulation, inheritance, polymorphism, interfaces, abstract classes, virtual methods, classes, sealed classes, and provides code examples for foreach loops, switch statements, arrays, data types, boxing and unboxing, overloading and overriding, interfaces, classes vs. structures, access modifiers, abstract classes, and sealed classes.
This document provides information on input/output operations, file handling, and serialization in Java. It discusses Java's input and output streams for reading and writing bytes and characters. It describes classes for working with files like File, FileInputStream, FileOutputStream, FileReader, and FileWriter. Examples are given for reading from and writing to files and the console. The document also introduces serialization in Java for converting objects to byte streams for storage or transmission.
Scala for Java Developers provides an overview of Scala for Java developers. It discusses:
- The goals of understanding what Scala is, learning more about it, and installing Scala.
- An introduction to Scala including what it is, its history from 1995 to 2013, and whether it is a good fit for certain uses based on its strengths like functional programming and weaknesses like syntax.
- How to get started with Scala including required and optional software and plugins.
- Key Scala features like objects, classes, traits, pattern matching, and collections.
Slides for invited talk at Dynamic Languages Symposium (DLS'15) at SPLASH 2015 in Pittsburgh
http://2015.splashcon.org/event/dls2015-papers-declare-your-language
In the Language Designer’s Workbench project we are extending the Spoofax Language Workbench with meta-languages to declaratively specify the syntax, name binding rules, type rules, and operational semantics of a programming language design such that a variety of artifacts including parsers, static analyzers, interpreters, and IDE editor services can be derived and properties can be verified automatically. In this presentation I will talk about declarative specification for two aspects of language design: syntax and name binding.
First, I discuss the idea of declarative syntax definition as supported by grammar formalisms based on generalized parsing using the SDF3 syntax definition formalism as example. With SDF3, the language designer defines syntax in terms of productions and declarative disambiguation rules. This requires understanding a language in term of (tree) structure instead of the operational implementation of parsers. As a result, syntax definitions can be used for a range of language processors including parsers, formatters, syntax coloring, outline view, syntactic completion.
Second, I discuss our recent work on the declarative specification of name binding rules, that takes inspiration from declarative syntax definition. The NaBL name binding language supports definition of name binding rules in terms of its fundamental concepts: declarations, references, scopes, and imports. I will present the theory of name resolution that we have recently developed to provide a semantics for name binding languages such as NaBL.
Classes allow users to bundle data and functions together. A class defines data members and member functions. Data members store data within each object, while member functions implement behaviors. Classes support access specifiers like public and private to control access to members. Objects are instances of classes that allocate memory for data members. Member functions can access object data members and are called on objects using dot notation. Friend functions allow non-member functions to access private members of classes.
The document discusses object-oriented programming concepts including encapsulation, inheritance, and polymorphism. It provides an example class called Point that demonstrates defining data members and member functions. It then provides a more detailed example of a Set class that implements common set operations like adding/removing elements and computing intersections/unions. The document also discusses constructors and destructors and how they are used to initialize and clean up class objects.
The Ring programming language version 1.4 book - Part 9 of 30Mahmoud Samir Fayed
This document provides documentation on Ring programming language classes, functions, and objects. It includes sections on getting class and method names, checking types, accessing and modifying object attributes and methods, and sharing methods between classes without inheritance. Various functions are described like classes(), isclass(), attributes(), methods(), addattribute(), and setattribute(). Examples are provided to illustrate the usage of each function.
The document discusses classes, objects, and methods in object-oriented programming. It introduces the Dice class as an example, which models the behavior and properties of dice. The Dice class has private member variables to store the number of sides and rolls, and public methods like Roll() and NumSides() to access and manipulate these properties. The document explains concepts like encapsulation, properties, static methods, and the importance of classes and objects in organizing code into reusable components.
The Ring programming language version 1.2 book - Part 22 of 84Mahmoud Samir Fayed
The document provides documentation on Ring programming language functions for working with classes, objects, attributes and methods. It describes functions such as classes(), packageclasses(), isclass(), classname(), objectid(), isobject(), attributes(), methods(), isattribute(), addattribute(), addmethod(), getattribute(), and setattribute(). Examples are given showing how to use each function to get information about classes and objects, check types, add/get/set attributes and methods, etc.
The Ring programming language version 1.5.2 book - Part 32 of 181Mahmoud Samir Fayed
The document provides documentation on Ring programming language functions for working with classes, objects, attributes and methods. It summarizes over 40 functions, including classes() to get class names, isclass() to check if a class exists, packageclasses() to get classes in a package, addattribute() to add attributes to an object, and getattribute()/setattrbute() to get/set attribute values. Examples are given for each function.
The Ring programming language version 1.4.1 book - Part 9 of 31Mahmoud Samir Fayed
This document summarizes reflection and meta-programming functions in the Ring programming language. It describes functions to get information about code at runtime like variable names, functions, classes and more. It also describes functions to check and modify objects, like getting/adding attributes, checking if an attribute exists, and more. These meta-programming capabilities allow Ring programs to introspect and modify their own code and objects at runtime.
Principles of functional progrmming in scalaehsoon
a short outline on necessity of functional programming and principles of functional programming in Scala.
In the article some keyword are used but not explained (to keep the article short and simple), the interested reader can look them up in internet.
This document summarizes advanced JavaScript concepts including:
- Object-oriented inheritance patterns in JavaScript and trends toward avoiding new and emulating private members. Pseudo-classical inheritance is recommended for better performance.
- Exploiting JavaScript's support for functional programming with higher-order functions to allow functions as arguments and return values for more flexible programming.
- Common issues with asynchronous code in JavaScript and how promises can help address callbacks and synchronization.
- Common pitfalls to avoid with arrays, numbers, and typeof in JavaScript.
Slides from my talk at the Junction (Jan 24, 2013)
Single-core performance has hit a ceiling, and building web-scale multi-core applications using imperative programming models is nightmarishly difficult. Parallel programming creates a new set of challenges, best practices and design patterns. Scala is designed to enable building scalable systems, elegantly blending functional and object oriented paradigms into an expressive and concise language, while retaining interoperability with Java. Scala is the fastest growing JVM programming language, being rapidly adopted by leading companies such as Twitter, LinkedIn and FourSquare.
This presentation provides a comprehensive overview of the language, which managed to increase type safety while feeling more dynamic, being more concise and improving readability at the same time. We will see how Scala simplifies real life problems by empowering the developer with powerful functional programming primitives, without giving up on the object oriented paradigm. The overview includes tools for multi-core programming in Scala, the type system, collection framework and domain-specific languages. We’ll explore the power of compile-time meta-programming, which is made possible by the newly released Scala 2.10, and get a glimpse into what to expect from 2.11 in 2014.
We will also see how Scala helps overcome the inherent limitations of Java, such as type erasure, array covariance and boxing overhead.
Multiple examples emphasize how Scala pushes the JVM harder than any other mainstream language through the infinite number of boilerplate busters, increased type safety and productivity boosters from a Java developer’s perspective.
The Ring programming language version 1.9 book - Part 41 of 210Mahmoud Samir Fayed
This document provides summaries of Ring programming functions related to classes and objects. It describes functions for getting class names and checking class definitions, getting classes within packages, and checking class and attribute definitions. It also summarizes functions for working with objects, including getting/setting attributes and methods, checking if an object or attribute exists, and adding attributes and methods to objects. Examples are provided to demonstrate the usage of each function.
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
Scala is a programming language that combines object-oriented and functional programming. It runs on the JVM and is interoperable with Java. Scala is statically typed and concise.
Scala allows modeling of concepts like rational numbers and mutable cells. Classes can implement traits to mix in functionality like logging. Pattern matching makes deconstructing data structures like lists and optional values easy. The Scala library includes collections, functions, and other functional programming constructs.
The Ring programming language version 1.3 book - Part 22 of 88Mahmoud Samir Fayed
The document provides an overview of functional programming concepts in Ring, including pure functions, first-class functions, higher-order functions, and anonymous functions. It defines pure functions as functions that do not change state by copying function parameters rather than modifying original values. It also explains that in Ring, functions are first-class citizens that can be passed as parameters, returned as values, or stored in variables, and demonstrates how to call a function stored in a variable.
This document provides an introduction and overview of inheritance in C#, including:
- Inheritance allows classes to extend existing classes, inheriting members and behavior
- Derived classes can call base class constructors via the base keyword
- The protected keyword controls accessibility for inherited members
- Virtual and override enable dynamic binding and polymorphism by allowing derived classes to override base class methods
- Abstract classes define common interfaces for derived classes to implement
The Ring programming language version 1.5.2 book - Part 37 of 181Mahmoud Samir Fayed
This document discusses using the Ring programming language to create natural language programs based on classes and objects. It provides an example of defining classes to represent the natural language instructions "I want window" and "Window title =". The example shows how objects can execute code for each instruction. The document also discusses changing the Ring keyword "and" to avoid conflicts when parsing natural language statements. In summary, this document demonstrates how Ring allows programmers to build natural language interfaces by defining classes for natural language statements.
Scala is a multi-paradigm programming language that runs on the JVM. It combines object-oriented and functional programming concepts. SBT is the build tool used for Scala projects and allows for incremental compilation. Scala has a uniform approach to collections that emphasizes immutability and uses higher-order
The document discusses various object-oriented programming concepts in C#, including abstraction, encapsulation, inheritance, polymorphism, interfaces, abstract classes, virtual methods, classes, sealed classes, and provides code examples for foreach loops, switch statements, arrays, data types, boxing and unboxing, overloading and overriding, interfaces, classes vs. structures, access modifiers, abstract classes, and sealed classes.
This document provides information on input/output operations, file handling, and serialization in Java. It discusses Java's input and output streams for reading and writing bytes and characters. It describes classes for working with files like File, FileInputStream, FileOutputStream, FileReader, and FileWriter. Examples are given for reading from and writing to files and the console. The document also introduces serialization in Java for converting objects to byte streams for storage or transmission.
Scala for Java Developers provides an overview of Scala for Java developers. It discusses:
- The goals of understanding what Scala is, learning more about it, and installing Scala.
- An introduction to Scala including what it is, its history from 1995 to 2013, and whether it is a good fit for certain uses based on its strengths like functional programming and weaknesses like syntax.
- How to get started with Scala including required and optional software and plugins.
- Key Scala features like objects, classes, traits, pattern matching, and collections.
Slides for invited talk at Dynamic Languages Symposium (DLS'15) at SPLASH 2015 in Pittsburgh
http://2015.splashcon.org/event/dls2015-papers-declare-your-language
In the Language Designer’s Workbench project we are extending the Spoofax Language Workbench with meta-languages to declaratively specify the syntax, name binding rules, type rules, and operational semantics of a programming language design such that a variety of artifacts including parsers, static analyzers, interpreters, and IDE editor services can be derived and properties can be verified automatically. In this presentation I will talk about declarative specification for two aspects of language design: syntax and name binding.
First, I discuss the idea of declarative syntax definition as supported by grammar formalisms based on generalized parsing using the SDF3 syntax definition formalism as example. With SDF3, the language designer defines syntax in terms of productions and declarative disambiguation rules. This requires understanding a language in term of (tree) structure instead of the operational implementation of parsers. As a result, syntax definitions can be used for a range of language processors including parsers, formatters, syntax coloring, outline view, syntactic completion.
Second, I discuss our recent work on the declarative specification of name binding rules, that takes inspiration from declarative syntax definition. The NaBL name binding language supports definition of name binding rules in terms of its fundamental concepts: declarations, references, scopes, and imports. I will present the theory of name resolution that we have recently developed to provide a semantics for name binding languages such as NaBL.
Model-Driven Software Development - Static Analysis & Error CheckingEelco Visser
The document discusses static analysis and error checking, including name resolution, type analysis, and checking for consistency. It describes analyzing syntax definitions, performing static analysis to check consistency beyond well-formedness, and reporting errors. Key aspects covered include type analysis, name resolution, reference resolution, and checking constraints.
Ciência e tecnologia no brasil #c&t #inovacaoHilton M
Este documento resume a política de ciência e tecnologia no Brasil no passado recente, analisa as transformações atuais no contexto internacional e faz recomendações para uma nova política no futuro. As principais conclusões são: (1) a política anterior de C&T precisa ser reformulada para se adequar às novas realidades econômicas e globais; (2) é necessário redirecionar os investimentos em C&T para áreas aplicadas que beneficiem a economia, preservar a capacitação científica existente e apoiar a ciência básica;
Introduction - Imperative and Object-Oriented LanguagesGuido Wachsmuth
This document provides an overview of imperative and object-oriented languages. It discusses the properties of imperative languages like state, statements, control flow, procedures and types. It then covers object-oriented concepts like objects, messages, classes, inheritance and polymorphism. Examples are given in various languages like C, Java bytecode, x86 assembly to illustrate concepts like variables, expressions, functions and object-oriented features. Finally, it provides an outlook on upcoming lectures covering declarative language definition.
Declarative Semantics Definition - Static Analysis and Error CheckingGuido Wachsmuth
The document discusses static analysis and error checking in compiler construction. It covers several key topics:
- The static analysis process of parsing source code, checking for errors, and generating machine code.
- Name analysis, binding, and scoping during static checking and for editor services like refactoring and code generation.
- Testing static semantics including name binding, type systems, and constraints.
- Restricting context-free languages using static semantics and judgements of well-formedness and well-typedness.
- Formal type systems including those for Tiger language examples involving types, expressions, and scoping.
Declarative Semantics Definition - Term RewritingGuido Wachsmuth
This document discusses term rewriting and its applications in compiler construction. It covers term rewriting systems, rewrite rules that transform terms, and rewrite strategies that control rule application. Examples are provided for desugaring code using rewrite rules and constant folding arithmetic expressions using rewrite rules and strategies. Stratego is presented as a domain-specific language for program transformation based on term rewriting.
The document discusses functional programming concepts in Scala including creating immutable objects to represent rational numbers, using pattern matching to add rationals, and defining classes with private fields and auxiliary constructors while avoiding side effects through immutable and functional design. It provides examples of functional programming techniques like creating rational number objects that are immutable and can be freely passed around without risk of mutation, and defining methods as functions that take arguments instead of mutating object state.
Functional objects are immutable objects that do not have mutable state. They allow functions to be passed as arguments and returned from other functions. The document introduces functional objects using the example of a Rational number class in Scala. It demonstrates how to define a Rational class with immutable fields and methods like addition, constructors, and equality checks.
Scala is a multi-paradigm programming language that supports functional, object-oriented and imperative programming paradigms. The document discusses Scala's support for types, expressions, objects, functions, and provides examples of using Scala for expressions, functions, control structures, patterns, spaces and actors.
Classes allow programmers to create new types that model real-world objects. A class defines both data attributes and built-in operations that can operate on that data. C++ provides built-in classes like string and iostream that add powerful functionality to the language. The string class allows easy storage and manipulation of strings, while the iostream classes (istream and ostream) define objects like cin and cout for input/output. These classes provide many useful built-in operations that make input/output powerful yet easy to use.
Arrays are data structures that store a collection of data elements of the same type using a single variable name to represent the entire collection. Structures group together data of different types under one name. Sparse matrices represent matrices with many zero elements by only storing the non-zero elements, using triples of row, column, and value to represent each non-zero term. Transposing a sparse matrix involves taking each non-zero term <i,j,value> and storing it as <j,i,value> in the transpose.
The Ring programming language version 1.5.2 book - Part 30 of 181Mahmoud Samir Fayed
This document summarizes object-oriented programming concepts in Ring including classes, objects, attributes, methods, inheritance, composition, and more. It provides examples of how to define classes with attributes and methods, create objects, access object attributes and call methods using dot notation and braces. It also covers more advanced topics like private/public members, operator overloading, packages, sorting/searching lists of objects, and dynamic attributes.
This document discusses arrays and structures. It begins by defining an array as a set of index and value pairs where each index has an associated value. Arrays can be implemented using consecutive memory locations. Structures allow grouping of different data types together. Self-referential structures have one or more components that point back to the structure itself. Examples of abstract data types discussed include arrays, polynomials, and sparse matrices. Common operations on these data types like addition, multiplication, and transposition are also described.
The document discusses functions in C++. It defines functions as modules that can be called to break programs into smaller pieces, making code easier to design, build, debug and maintain. It provides examples of function definitions and calls. Functions take arguments, make copies of them, perform tasks, and return results. Function prototypes specify argument and return types. Well-designed programs use preexisting and new functions to organize and reuse code.
The Ring programming language version 1.2 book - Part 20 of 84Mahmoud Samir Fayed
This document provides documentation on object-oriented programming concepts in Ring including:
- Defining classes with attributes and methods
- Accessing object attributes using dot notation and braces
- Composition of objects as attributes of other objects
- Defining setter and getter methods
- Private and public attributes and methods
- Operator overloading for classes
- Inheritance between classes
- Dynamic attributes defined at runtime
- Packages to organize classes
- Printing and finding objects in lists
- Sorting lists of objects
It includes examples of implementing each concept and the output of running the example code.
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
The document discusses key concepts in Java classes and objects including constructors, method overloading, and static members. Constructors allow objects to be initialized when created and can have different signatures to support multiple initialization options. Method overloading allows multiple methods with the same name but different parameters, while static members like variables and methods exist independently of any object and can be accessed via the class name. The document provides examples demonstrating how to define and use constructors, overloaded methods, and static members when working with classes in Java.
Kotlin is a concise, safe, and statically typed programming language that compiles to JVM bytecode and JavaScript. It focuses on interoperability with Java and solves many Java pitfalls. Kotlin removes verbosity like semicolons and replaces "extends" and "implement" with a colon. Functions are defined with the "fun" keyword and return types follow. Properties are treated like fields. Kotlin avoids null references through null safety features like the safe call operator and non-null assertion operator. When expressions replace switch statements. Extension functions can extend existing classes without subclassing.
This document provides an agenda and overview for a Spark workshop covering Spark basics and streaming. The agenda includes sections on Scala, Spark, Spark SQL, and Spark Streaming. It discusses Scala concepts like vals, vars, defs, classes, objects, and pattern matching. It also covers Spark RDDs, transformations, actions, sources, and the spark-shell. Finally, it briefly introduces Spark concepts like broadcast variables, accumulators, and spark-submit.
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
Slides I prepared for the 29 January 2014 Ecma TC39 meeting, on Value Objects in JS, an ES7 proposal -- this one shotgunned the roadmap-space of declarative syntax, to find the right amount per TC39 (nearly zero, turns out).
This document summarizes arrays and structures in C including:
1) Arrays are sets of index-value pairs that use consecutive memory locations. Structures group related data and can reference themselves.
2) C implements 1D arrays using consecutive memory locations accessed via indexes. Structures allow defining custom data types.
3) Operations on ordered lists include retrieving, inserting, deleting elements. Polynomials are represented as ordered pairs of exponents and coefficients. Addition involves comparing exponents and combining coefficients.
I am Irene M. I am a C++ Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from from California, USA. I have been helping students with their homework for the past 10 years. I solve homework related to C++.
Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Homework.
1. The document discusses a lecture on object oriented programming in C++. It introduces classes and objects, and explains how to declare a class and create objects in C++.
2. It provides an example class called CRectangle with data members and member functions to demonstrate class structure and how to define functions inside and outside the class.
3. The lecture concludes with providing some examples programs to demonstrate class concepts and exercises for students to practice.
The Ring programming language version 1.5.3 book - Part 31 of 184Mahmoud Samir Fayed
This document provides a summary of key Ring programming language concepts related to functional programming, including pure functions, first-class functions, higher-order functions, anonymous functions, and testing equality of functions. It includes examples of defining pure functions that avoid side effects by copying rather than mutating passed arguments, passing functions as parameters and returning functions from other functions, using anonymous functions, and applying functions to lists via map-style functions.
The Ring programming language version 1.8 book - Part 86 of 202Mahmoud Samir Fayed
This document discusses the Ring2EXE tool for compiling Ring code to executables and provides documentation on low-level Ring functions. It introduces the ring2exe command for building executables and notes that project and main files need to be copied to the application folder. It then summarizes several low-level Ring functions for memory management, pointers, tracing, and introspection.
Martin Odersky received his PhD in 1989 and began designing Scala in 2001 at EPFL. Scala is a functional and object-oriented programming language that runs on the Java Virtual Machine. It is concise, high-level, statically typed, and supports both immutable and mutable data structures. Many large companies use Scala including LinkedIn, Twitter, and Ebay. Scala supports both object-oriented programming with classes, traits, and objects as well as functional programming with immutable data, higher-order functions, and algebraic data types.
This document discusses first-class functions and lambda calculus. It begins with an overview of Alonzo Church and the origins of lambda calculus. It then covers first-class functions in JavaScript, functions as objects in Java, and first-class functions in Scala. The document also discusses generic higher-order functions and control abstraction.
This document discusses syntactic editor services including formatting, syntax coloring, and syntactic completion. It describes how syntactic completion can be provided generically based on a syntax definition. The document also discusses how context-free grammars can be extended with templates to specify formatting layout when pretty-printing abstract syntax trees to text. Templates are used to insert whitespace, line breaks, and indentation to produce readable output.
This document provides an overview of parsing in compiler construction. It discusses context-free grammars and how they are used to generate sentences and parse trees through derivations. It also covers ambiguity that can arise from grammars and various grammar transformations used to eliminate ambiguity, including defining associativity and priority. The dangling else problem is presented as an example of an ambiguous grammar.
This document provides an overview of the Lecture 2 on Declarative Syntax Definition for the CS4200 Compiler Construction course. The lecture covers the specification of syntax definition from which parsers can be derived, the perspective on declarative syntax definition using SDF, and reading material on the SDF3 syntax definition formalism and papers on testing syntax definitions and declarative syntax. It also discusses what syntax is, both in linguistics and programming languages, and how programs can be described in terms of syntactic categories and language constructs. An example Tiger program for solving the n-queens problem is presented to illustrate syntactic categories in Tiger.
This document provides an overview of the CS4200 Compiler Construction course at TU Delft. It discusses the course organization, structure, and assessment. The course is split into two parts - CS4200-A which covers concepts and techniques through lectures, papers, and homework assignments, and CS4200-B which involves building a compiler for a subset of Java as a semester-long project. Students will use the Spoofax language workbench to implement their compiler and will submit assignments through a private GitLab repository.
A Direct Semantics of Declarative Disambiguation RulesEelco Visser
This document discusses research into providing a direct semantics for declarative disambiguation of expression grammars. It aims to define what disambiguation rules mean, ensure they are safe and complete, and provide an effective implementation strategy. The document outlines key research questions around the meaning, safety, completeness and coverage of disambiguation rules. It also presents contributions around using subtree exclusion patterns to define safe and complete disambiguation for classes of expression grammars, and implementing this in SDF3.
Declarative Type System Specification with StatixEelco Visser
In this talk I present the design of Statix, a new constraint-based language for the executable specification of type systems. Statix specifications consist of predicates that define the well-formedness of language constructs in terms of built-in and user-defined constraints. Statix has a declarative semantics that defines whether a model satisfies a constraint. The operational semantics of Statix is defined as a sound constraint solving algorithm that searches for a solution for a constraint. The aim of the design is that Statix users can ignore the execution order of constraint solving and think in terms of the declarative semantics.
A distinctive feature of Statix is its use of scope graphs, a language parametric framework for the representation and querying of the name binding facts in programs. Since types depend on name resolution and name resolution may depend on types, it is typically not possible to construct the entire scope graph of a program before type constraint resolution. In (algorithmic) type system specifications this leads to explicit staging of the construction and querying of the type environment (class table, symbol table). Statix automatically stages the construction of the scope graph of a program such that queries are never executed when their answers may be affected by future scope graph extension. In the talk, I will explain the design of Statix by means of examples.
https://eelcovisser.org/post/309/declarative-type-system-specification-with-statix
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionEelco Visser
Compiler construction techniques are applied beyond general-purpose languages through domain-specific languages (DSLs). The document discusses several DSLs developed using Spoofax including:
- WebDSL for web programming with sub-languages for entities, queries, templates, and access control.
- IceDust for modeling information systems with derived values computed on-demand, incrementally, or eventually consistently.
- PixieDust for client-side web programming with views as derived values updated incrementally.
- PIE for defining software build pipelines as tasks with dynamic dependencies computed incrementally.
The document also outlines several research challenges in compiler construction like high-level declarative language definition, verification of
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Eelco Visser
This document discusses domain-specific languages (DSLs) for parallel graph analytics using PGX. It describes how DSLs allow users to implement graph algorithms and queries using high-level languages that are then compiled and optimized to run efficiently on PGX. Examples of DSL optimizations like multi-source breadth-first search are provided. The document also outlines the extensible compiler architecture used for DSLs, which can generate code for different backends like shared memory or distributed memory.
Compiler Construction | Lecture 15 | Memory ManagementEelco Visser
The document discusses different memory management techniques:
1. Reference counting counts the number of pointers to each record and deallocates records with a count of 0.
2. Mark and sweep marks all reachable records from program roots and sweeps unmarked records, adding them to a free list.
3. Copying collection copies reachable records to a "to" space, allowing the original "from" space to be freed without fragmentation.
4. Generational collection focuses collection on younger object generations more frequently to improve efficiency.
Compiler Construction | Lecture 14 | InterpretersEelco Visser
This document summarizes a lecture on interpreters for programming languages. It discusses how operational semantics can be used to define the meaning of a program through state transitions in an interpreter. It provides examples of defining the semantics of a simple language using DynSem, a domain-specific language for specifying operational semantics. DynSem specifications can be compiled to interpreters that execute programs in the defined language.
Compiler Construction | Lecture 13 | Code GenerationEelco Visser
The document discusses code generation and optimization techniques, describing compilation schemas that define how language constructs are translated to target code patterns, and covers topics like ensuring correctness of generated code through type checking and verification of static constraints on the target format. It also provides examples of compilation schemas for Tiger language constructs like arithmetic expressions and control flow and discusses generating nested functions.
Compiler Construction | Lecture 12 | Virtual MachinesEelco Visser
The document discusses the architecture of the Java Virtual Machine (JVM). It describes how the JVM uses threads, a stack, heap, and method area. It explains JVM control flow through bytecode instructions like goto, and how the operand stack is used to perform operations and hold method arguments and return values.
Compiler Construction | Lecture 9 | Constraint ResolutionEelco Visser
This document provides an overview of constraint resolution in the context of a compiler construction lecture. It discusses unification, which is the basis for many type inference and constraint solving approaches. It also describes separating type checking into constraint generation and constraint solving, and introduces a constraint language that integrates name resolution into constraint resolution through scope graph constraints. Finally, it discusses papers on further developments with this approach, including addressing expressiveness and staging issues in type systems through the Statix DSL for defining type systems.
Compiler Construction | Lecture 8 | Type ConstraintsEelco Visser
This lecture covers type checking with constraints. It introduces the NaBL2 meta-language for writing type specifications as constraint generators that map a program to constraints. The constraints are then solved to determine if a program is well-typed. NaBL2 supports defining name binding and type structures through scope graphs and constraints over names, types, and scopes. Examples show type checking patterns in NaBL2 including variables, functions, records, and name spaces.
Compiler Construction | Lecture 7 | Type CheckingEelco Visser
This document summarizes a lecture on type checking. It discusses using constraints to separate the language-specific type checking rules from the language-independent solving algorithm. Constraint-based type checking collects constraints as it traverses the AST, then solves the constraints in any order. This allows type information to be learned gradually and avoids issues with computation order.
Compiler Construction | Lecture 6 | Introduction to Static AnalysisEelco Visser
Lecture introducing the need for static analysis in addition to parsing, the complications caused by names, and an introduction to name resolution with scope graphs
5. Binding Variable Identifiers
name binding
binding
defining occurrence
val msg = "Hello, " + "world!"
println(msg)
applied occurrence
val variables cannot be rebound
B:6.1 TI 1220 - Lecture 2: Functional Objects 5
6. Binding Variable Identifiers
name binding
binding
defining occurrence
var greeting = "Hello, world!"
greeting = "Leave me alone, world!"
rebinding
var variables can be rebound
B:6.1 TI 1220 - Lecture 2: Functional Objects 6
7. Binding Function Identifiers
name binding
binding
defining occurrence
def widthOfLength(s: String) =
s.length.toString.length
val maxWidth = widthOfLength(longestLine)
applied occurrence
B:6.1 TI 1220 - Lecture 2: Functional Objects 7
8. Binding Class Identifiers
name binding
binding
defining occurrence
class ChecksumAccumulator {
var sum = 0
}
var acc = new ChecksumAccumulator
var csa = new ChecksumAccumulator
acc.sum = 3
csa = acc applied occurrence
TI 1220 - Lecture 2: Functional Objects 8
9. Rebinding vs Mutation
name binding
class ChecksumAccumulator {
var sum = 0
} binding
var acc = new ChecksumAccumulator
var csa = new ChecksumAccumulator
mutation
acc.sum = 3
csa = acc
rebinding
TI 1220 - Lecture 2: Functional Objects 9
10. Name Spaces
name binding
object foo {
val foo : Int = 0
def foo(x : Int) = x + 1
}
object bar {
def bar() = foo.foo(foo.foo)
}
variables, functions, objects are in separate name spaces
B:6.1 TI 1220 - Lecture 2: Functional Objects 10
11. Substitution
name binding
val msg = "Hello, " + "world!"
println(msg)
?
println("Hello, " + "world!")
can we replace applied occurrence with bound expression/value?
B:6.1 TI 1220 - Lecture 2: Functional Objects 11
14. Constructing a Rational
class parameters
class Rational(n: Int, d: Int) {
println("Created " + n + "/" + d)
}
scala> new Rational(1, 2)
Created 1/2
res0: Rational = Rational@2d83e895
B:6.2 TI 1220 - Lecture 2: Functional Objects 14
15. Immutable Object Trade-offs
Advantages
• easier reasoning
• pass around freely (no risk of undesired mutations)
• cannot be changed concurrently in two threads
• immutable object make safe hashtable keys
Disadvantages
• copying large object graphs vs in-place update
B:6.1 TI 1220 - Lecture 2: Functional Objects 15
16. Reimplementing toString
overriding methods
class Rational(n: Int, d: Int) {
override def toString = n + "/" + d
}
scala> val half = new Rational(1, 2)
half: Rational = 1/2
B:6.3 TI 1220 - Lecture 2: Functional Objects 16
17. Checking Preconditions
class Rational(n: Int, d: Int) {
require(d != 0)
override def toString = n + "/" + d
}
scala> val half = new Rational(1, 0)
java.lang.IllegalArgumentException: requirement failed
B:6.4 TI 1220 - Lecture 2: Functional Objects 17
18. Visibility of Class Parameters
class Rational(n: Int, d: Int) {
require(d != 0)
override def toString = n + "/" + d
def add(that: Rational): Rational =
new Rational(n * that.d + that.n * d, d * that.d)
}
$ fsc Rational.scala
Rational.scala:5: error: value d is not a member of Rational
new Rational(n * that.d + that.n * d, d * that.d)
^
Rational.scala:5: error: value d is not a member of Rational
new Rational(n * that.d + that.n * d, d * that.d)
^
two errors found
B:6.5 TI 1220 - Lecture 2: Functional Objects 18
19. Adding Fields
class Rational(n: Int, d: Int) {
require(d != 0)
val numer: Int = n
val denom: Int = d
override def toString = numer + "/" + denom
def add(that: Rational): Rational =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom)
}
scala> new Rational(1,2) add new Rational(2,3)
res0: Rational = 7/6
B:6.5 TI 1220 - Lecture 2: Functional Objects 19
20. Non-Functional Objects
destructive update
class ImperativeRational(n: Int, d: Int) {
require(d != 0)
var numer: Int = n
var denom: Int = d
override def toString = numer + "/" + denom
def add(that: ImperativeRational) {
numer = numer * that.denom + that.numer * denom;
denom = denom * that.denom;
}
} scala> val half = new ImperativeRational(1, 2)
half: ImperativeRational = 1/2
scala> val twothirds = new ImperativeRational(2,3)
twothirds: ImperativeRational = 2/3
scala> half.add(twothirds)
scala> half
res1: ImperativeRational = 7/6
B:6.1 TI 1220 - Lecture 2: Functional Objects 20
21. Self References
this
def lessThan(that: Rational) =
this.numer * that.denom < that.numer * this.denom
def max(that: Rational) =
if (this.lessThan(that)) that else this
B:6.6 TI 1220 - Lecture 2: Functional Objects 21
22. Auxiliary Constructors
class Rational(n: Int, d: Int) {
require(d != 0)
val numer = n
val denom = d
def this(n: Int) = this(n, 1) // auxiliary constructor
...
}
scala> new Rational(6)
res1: Rational = 6/1
B:6.7 TI 1220 - Lecture 2: Functional Objects 22
23. Private Fields and Methods
class Rational(n: Int, d: Int) {
require(d != 0)
private val g = gcd(n.abs, d.abs)
val numer = n / g
val denom = d / g
...
private def gcd(a: Int, b: Int): Int =
if (b == 0) a else gcd(b, a % b)
}
scala> new Rational(6,42)
res1: Rational = 1/7
B:6.7 TI 1220 - Lecture 2: Functional Objects 23
24. Defining Operators
use functions as infix operators
def add(that: Rational): Rational =
new Rational(numer * that.denom + that.numer * denom,
denom * that.denom)
scala> new Rational(1,2).add(new Rational(2,3))
res0: Rational = 7/6
scala> new Rational(1,2) add new Rational(2,3)
res0: Rational = 7/6
B:6.7 TI 1220 - Lecture 2: Functional Objects 24
26. Defining Operators
operator identifiers
def +(that: Rational): Rational =
new Rational(numer * that.denom + that.numer * denom,
denom * that.denom)
def *(that: Rational): Rational =
new Rational(numer * that.numer, denom * that.denom)
scala> val d = a + b * c
d: Rational = 11/14
scala> val d = a.+(b.*(c))
d: Rational = 11/14
scala> val d = a * b + c
d: Rational = 16/21
scala> val d = (a.*(b)).+(c)
d: Rational = 16/21
B:6.7 TI 1220 - Lecture 2: Functional Objects 26
27. Identifiers
lexical syntax
Alphanumeric identifier
• identifier: [$A-Za-z_][$A-Za-z_0-9]* ($ reserved for Scala compiler)
• camel-case convention: toString, HashSet
Operator identifier
• Unicode set of mathematical symbols(Sm) or other symbols(So), or to
the 7-bit ASCII characters that are not letters, digits, parentheses,
square brackets, curly braces, single or double quote, or an underscore,
period,semi-colon, comma, or back tick character.
Literal Identifier
• arbitrary string enclosed in back ticks (` . . . `).
B:6.1 TI 1220 - Lecture 2: Functional Objects 27
28. Method Overloading
for different argument types
def *(that: Rational): Rational =
new Rational(numer * that.numer, denom * that.denom)
def *(i: Int): Rational =
new Rational(numer * i, denom)
scala> val c = new Rational(3,7)
c: Rational = 3/7
scala> c * 2
res1: Rational = 6/7
B:6.1 TI 1220 - Lecture 2: Functional Objects 28
29. Method Overloading
does not apply to this
def *(that: Rational): Rational =
new Rational(numer * that.numer, denom * that.denom)
def *(i: Int): Rational =
new Rational(numer * i, denom)
scala> 2 * c
<console>:7: error: overloaded method value * with alternatives: (Double)
Double <and> (Float)Float <and> (Long)Long <and> (Int)Int <and> (Char)Int
<and> (Short)Int <and> (Byte)Int cannot be applied to (Rational)
2 * c
^
B:6.1 TI 1220 - Lecture 2: Functional Objects 29
30. Implicit Conversions
def *(that: Rational): Rational =
new Rational(numer * that.numer, denom * that.denom)
def *(i: Int): Rational =
new Rational(numer * i, denom)
implicit def intToRational(x: Int) = new Rational(x)
scala> 2 * c
res4: Rational = 6/7
B:6.1 TI 1220 - Lecture 2: Functional Objects 30
31. Summary
functional objects
Immutable objects
• class parameters
• immutable fields (val)
• methods don’t change object, but return value
Natural, concise notation
• methods as infix operators, operator identifiers
• method overloading
• implicit conversion
B:6.1 TI 1220 - Lecture 2: Functional Objects 31
32. Exam Question
How many Rational objects are created while executing:
class Rational(n: Int, d: Int) {
require(d != 0)
val numer: Int = n
val denom: Int = d
override def toString = numer + "/" + denom
def +(that: Rational): Rational =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom)
}
var half = new Rational(1,2)
half = half + half + half
(a) 1
(b) 2
(c) 3
(d) 4
TI1220 - Introduction 32
35. Control-Flow Structures
Control-Flow Structures
• ordering execution
• choice, iteration, exception
Functional Control Structures
• can be used as expression
• return a value
Minimal set of built-in control structures
• control abstraction using function literals (next week)
B:6.1 TI 1220 - Lecture 2: Functional Objects 35
36. If Expressions
conditional choice
var filename = "default.txt"
if (!args.isEmpty) imperative style
filename = args(0)
val filename =
if (!args.isEmpty) args(0) functional style
else "default.txt"
B:7.1 TI 1220 - Lecture 2: Functional Objects 36
37. Equational Reasoning
replace equals by equals
val filename =
if (!args.isEmpty) args(0)
else "default.txt"
println(filename)
println(if (!args.isEmpty) args(0) else "default.txt")
B:7.1 TI 1220 - Lecture 2: Functional Objects 37
38. Equational Reasoning
replace equals by equals
val x = e; f(x) <=> f(e)
if e has no side effects
B:7.1 TI 1220 - Lecture 2: Functional Objects 38
39. While Loops
iteration
def gcdLoop(x: Long, y: Long): Long = {
var a = x
var b = y
while (a != 0) {
val temp = a
a = b % a
b = temp
}
b
}
B:7.2 TI 1220 - Lecture 2: Functional Objects 39
40. Do-While Loops
iteration
var line = ""
do {
line = readLine()
println("Read: " + line)
} while (line != "")
B:7.2 TI 1220 - Lecture 2: Functional Objects 40
41. Assignment has Type Unit
var line = ""
while ((line = readLine()) != "") // This doesn’t work!
println("Read: " + line)
B:7.2 TI 1220 - Lecture 2: Functional Objects 41
42. Iteration vs Recursion
def gcd(x: Long, y: Long): Long =
if (y == 0) x else gcd(y, x % y)
def gcdLoop(x: Long, y: Long): Long = {
var a = x
var b = y
while (a != 0) {
val temp = a
a = b % a
b = temp
}
b
}
B:7.2 TI 1220 - Lecture 2: Functional Objects 42
43. For Expressions
functional iteration
val filesHere = (new java.io.File(".")).listFiles
for (file <- filesHere)
println(file)
B:7.3 TI 1220 - Lecture 2: Functional Objects 43
44. Ranges
iterating over sequence of numbers
scala> for (i <- 1 to 4)
| println("Iteration " + i)
Iteration 1
Iteration 2
Iteration 3
Iteration 4
// Not common in Scala...
for (i <- 0 to filesHere.length - 1)
println(filesHere(i))
B:7.3 TI 1220 - Lecture 2: Functional Objects 44
45. Filtering
iterating over subset of a collection
for (file <- filesHere)
if (file.getName.endsWith(".scala"))
println(file)
for (file <- filesHere if file.getName.endsWith(".scala"))
println(file)
B:6.1 TI 1220 - Lecture 2: Functional Objects 45
46. Multiple Filters
for (
file <- filesHere if file.isFile;
if file.getName.endsWith(".scala")
) println(file)
B:7.3 TI 1220 - Lecture 2: Functional Objects 46
47. Nested Iteration
def fileLines(file: java.io.File) =
scala.io.Source.fromFile(file).getLines.toList
def grep(pattern: String) =
for (
file <- filesHere if file.getName.endsWith(".scala");
line <- fileLines(file) if line.trim.matches(pattern)
) println(file + ": " + line.trim)
grep(".*gcd.*")
B:7.3 TI 1220 - Lecture 2: Functional Objects 47
48. Mid-Stream Variable Binding
def grep(pattern: String) =
for {
file <- filesHere
if file.getName.endsWith(".scala")
line <- fileLines(file)
trimmed = line.trim
if trimmed.matches(pattern)
} println(file + ": " + trimmed)
grep(".*gcd.*")
B:7.3 TI 1220 - Lecture 2: Functional Objects 48
49. Producing a New Collection
yield
def scalaFiles =
for {
file <- filesHere
if file.getName.endsWith(".scala")
} yield file
B:7.3 TI 1220 - Lecture 2: Functional Objects 49
50. Composing filters
val forLineLengths =
for {
file <- filesHere
if file.getName.endsWith(".scala")
line <- fileLines(file)
trimmed = line.trim
if trimmed.matches(".*for.*")
} yield trimmed.length
B:7.3 TI 1220 - Lecture 2: Functional Objects 50
51. Throwing Exceptions
exception handling
val half =
if (n % 2 == 0)
n / 2
else
throw new RuntimeException("n must be even")
B:7.4 TI 1220 - Lecture 2: Functional Objects 51
52. Catching Exceptions
exception handling
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
try {
val f = new FileReader("input.txt")
// Use and close file
} catch {
case ex: FileNotFoundException => // Handle missing file
case ex: IOException => // Handle other I/O error
}
B:7.4 TI 1220 - Lecture 2: Functional Objects 52
54. Yielding a Value
exception handling
import java.net.URL
import java.net.MalformedURLException
def urlFor(path: String) =
try {
new URL(path)
} catch {
case e: MalformedURLException =>
new URL("http://www.scalalang.org")
}
B:7.4 TI 1220 - Lecture 2: Functional Objects 54
55. Match Expressions
choosing between actions
val firstArg = if (args.length > 0) args(0) else ""
firstArg match {
case "salt" => println("pepper")
case "chips" => println("salsa")
case "eggs" => println("bacon")
case _ => println("huh?")
}
B:7.5 TI 1220 - Lecture 2: Functional Objects 55
56. Match Expressions
choosing between values
val firstArg = if (!args.isEmpty) args(0) else ""
val friend =
firstArg match {
case "salt" => "pepper"
case "chips" => "salsa"
case "eggs" => "bacon"
case _ => "huh?"
}
println(friend)
B:7.5 TI 1220 - Lecture 2: Functional Objects 56
57. Break and Continue in Java
not in Scala
int i = 0; // This is Java
boolean foundIt = false;
while (i < args.length) {
if (args[i].startsWith("")) {
i = i + 1;
continue;
}
if (args[i].endsWith(".scala")) {
foundIt = true;
break;
}
i = i + 1;
}
B:7.6 TI 1220 - Lecture 2: Functional Objects 57
58. Replace Break/Continue with If ...
var i = 0
var foundIt = false
while (i < args.length && !foundIt) {
if (!args(i).startsWith("")) {
if (args(i).endsWith(".scala"))
foundIt = true
}
i = i + 1
}
B:7.6 TI 1220 - Lecture 2: Functional Objects 58
59. ... or with Recursion
def searchFrom(i: Int): Int =
if (i >= args.length) 1
else if (args(i).startsWith("")) searchFrom(i + 1)
else if (args(i).endsWith(".scala")) i
else searchFrom(i + 1)
val i = searchFrom(0)
B:7.6 TI 1220 - Lecture 2: Functional Objects 59
60. Variable Scope
almost identical to Java
Variables are declared in a scope
• { var j = 1; ... }
Inner scopes shadow variables in outer scopes
• { var j = 1; { var j = 2; ... } }
B:7.7 TI 1220 - Lecture 2: Functional Objects 60
62. def printMultiTable() {
var i = 1
// only i in scope here
while (i <= 10) {
var j = 1
// both i and j in scope here
while (j <= 10) {
val prod = (i * j).toString
// i, j, and prod in scope here
var k = prod.length
// i, j, prod, and k in scope here
while (k < 4) {
print(" ")
k += 1
}
print(prod)
j += 1
}
// i and j still in scope; prod and k out of scope
println()
i += 1
}
// i still in scope; j, prod, and k out of scope
}
B:7.7 TI 1220 - Lecture 2: Functional Objects 62
63. Refactoring Imperative-Style Code
// Returns a row as a sequence
def makeRowSeq(row: Int) =
for (col <- 1 to 10) yield {
val prod = (row * col).toString
val padding = " " * (4 - prod.length)
padding + prod
}
// Returns a row as a string
def makeRow(row: Int) = makeRowSeq(row).mkString
// Returns table as a string with one row per line
def multiTable() = {
val tableSeq = // a sequence of row strings
for (row <- 1 to 10)
yield makeRow(row)
tableSeq.mkString("n")
}
B:6.1 TI 1220 - Lecture 2: Functional Objects 63
65. Summary
lessons learned
Functional Objects
• immutable objects
• operations create new objects
Functional Control Structures
• return a value
• have a type
• can be used as expressions
TI 1220 - Lecture 2: Functional Objects 65
67. Exercises Week 2
complex numbers
Scala Test
• using unit testing framework to define executable tests
Complex numbers
• define class to represent complex numbers
• define tests
Note: all assignments should be done individually!
B:6.1 TI 1220 - Lecture 2: Functional Objects 67
70. Outlook
coming next
Lecture 3: Functions & Closures
• Chapters 8, 9
Lecture 4: List Programming
• Chapters 15, 16, 17
Lecture 5: Trees
• Chapters 26, 22, 23
Lab Week 2
• Complex numbers in Scala
B:6.1 TI 1220 - Lecture 2: Functional Objects 70
71. Exam Question (Week 1)
What happens when we execute the following code:
val greetStrings = new Array[String](3)
greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!n"
(a) Error: greetStrings is an immutable variable that cannot
be assigned to
(b) Error: Array is a immutable data structure that cannot
be assigned to
(c) No error: greetStrings is a mutable variable that can be
assigned to
(d) No error: Array is a mutable data structure that can be
assigned to
TI1220 - Introduction 71
72. Exam Question (Week 1)
What happens when we execute the following code:
val greetStrings = new Array[String](3)
greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!n"
(a) Error: greetStrings is an immutable variable that cannot
be assigned to
(b) Error: Array is a immutable data structure that cannot
be assigned to
(c) No error: greetStrings is a mutable variable that can be
assigned to
(d) No error: Array is a mutable data structure that can be
assigned to
TI1220 - Introduction 72
73. Exam Question (Week 2)
What is the return type of makeRowSeq:
def makeRowSeq(row: Int) =
for (col <- 1 to 10) yield {
val prod = (row * col).toString
val padding = " " * (4 - prod.length)
padding + prod
}
(a) String
(b) Int
(c) IndexedSeq[String]
(d) IndexedSeq[Int]
TI1220 - Introduction 73
74. Pictures
copyrights
Slide 1:
A Plumpish Proportion by SSG Robert Stewart some rights reserved
Slide 3:
McPhillips’ Map of the City of Winnipeg by Manitoba Historical Maps, some rights reserved
Slide 19:
Envelopes by benchilada, some rights reserved
Slide 20:
Report card by Carosaurus, some rights reserved
Slide 30:
Sun is Shining by el patojo, some rights reserved
B:6.1 TI 1220 - Lecture 2: Functional Objects 74
75. Pictures
copyrights
Slide:
Dinner at Roussillon (Martin Odersky) by Miles Sabin, some rights reserved
Slide:
Portrait: Alex Payne by Dave Fayram, some rights reserved
Slide:
“Plumbing Nightmare” by Natalie Wilkie, some rights reserved
Slide:
HIV: The Moleskine Summary by Niels Olson
Slide:
remember to thank all the books you haven’t read over the past three years
by Natalia Osiatynska, Some rights reserved
Slide:
Stupid Exam by Remi Carreiro, Some rights reserved
Slide:
Practice makes perfect by Simon Probert
http://www.flickr.com/photos/garrettc/3747802654/ Bombe detail by Garret Coakley, Some rights
reserved
B:6.1 TI 1220 - Lecture 2: Functional Objects 75