This document discusses whether Java 8 can be considered a true functional programming language. It begins with an overview of programming paradigms and compares the imperative and functional paradigms. It then outlines key aspects of functional programming including immutability, recursion, functions as first-class citizens, higher-order functions, and laziness. Code examples in Java demonstrate these concepts. The document concludes that while Java 8 incorporates some functional programming features, it does not fully embrace all aspects of functional programming.
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
The document discusses functional programming concepts like higher-order functions, function composition, currying, and lazy evaluation. It provides examples of implementing strategies like converting between units using functions and creating streams of prime numbers lazily to avoid stack overflows. Tail call optimization is mentioned as a way to avoid stack overflows with recursive functions.
This document discusses the history and evolution of functional programming in Java, including lambda expressions and streams. It describes how lambda expressions allow passing behaviors as arguments to methods like normal data. This improves API design, opportunities for optimization, and code readability. Streams encourage a lazy, pipelined style and can execute operations in parallel. Functional idioms like immutability and pure functions help enforce correctness and isolation of side effects.
The document discusses the introduction and advantages of lambda expressions and functional programming in Java 8. Some key points include:
- Lambda expressions allow passing behaviors as arguments to methods, simplifying code by removing bulky anonymous class syntax. This enables more powerful and expressive APIs.
- Streams provide a way to process collections of data in a declarative way, leveraging laziness to improve efficiency. Operations can be pipelined for fluent processing.
- Functional programming with immutable data and avoidance of side effects makes code more modular and easier to reason about, enabling optimizations like parallelism. While not natively supported, Java 8 features like lambda expressions facilitate a more functional approach.
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
The document discusses several key concepts in functional programming including:
- Immutable data and pure functions avoid side effects and allow for referential transparency.
- Higher order functions and avoiding mutable state enable concurrency and parallelism without data races.
- Programs can be designed with a pure functional core and push side effects to the outer layers for modularity.
Java 7, 8 & 9 - Moving the language forwardMario Fusco
The document summarizes new features in Java 7-8 including lambda expressions, switch on strings, try-with-resources, and the fork/join framework. Java 8 will focus on lambda expressions to provide functional programming capabilities and default methods to allow interfaces to have default implementations without breaking existing implementations. Java 9 may include additional modularization support.
The document discusses functional programming and lambda expressions in Java 8. It begins by defining functional programming and predicates from predicate logic. It then discusses the key properties of functional programming including no states, passing control, single large function, and no cycles. The document provides examples of determining if a number is prime in both imperative and declarative styles using Java 8 lambda expressions. It also provides examples of getting the first doubled number greater than 3 from a list using both declarative and imperative approaches. The examples demonstrate the use of streams, filters, maps and other functional operations.
This document discusses concurrency, scalability, and fault tolerance using actors and software transactional memory (STM) in Akka. It describes how actors provide message-passing concurrency by isolating processes and avoiding shared state. Actors allow easy reasoning about concurrency by preventing issues like race conditions and deadlocks. The document also covers how Akka implements actors, typed actors, remote actors, supervisor hierarchies for fault tolerance, and STM for coordinating concurrent changes to shared state transactionally. Combining actors with STM results in "transactors" that allow building distributed, concurrent, and fault-tolerant applications.
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Ontico
РИТ++ 2017, AppsConf
Зал Касабланка, 6 июня, 14:00
Тезисы:
http://appsconf.ru/2017/abstracts/2816.html
В докладе рассмотрим цену использования Kotlin в Runtime, обсудим варианты, как улучшить картину мира. Смотреть будем с точки зрения производительности, синхронно углубляясь в особенности Android, а также подумаем, как можно использовать получившийся байткод.
В докладе срыв подкапотных оптимизаций, байткод и цифры, которые покажут, насколько сильно вам смогут помочь все указанные оптимизации.
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
The document discusses functional programming concepts like higher-order functions, function composition, currying, and lazy evaluation. It provides examples of implementing strategies like converting between units using functions and creating streams of prime numbers lazily to avoid stack overflows. Tail call optimization is mentioned as a way to avoid stack overflows with recursive functions.
This document discusses the history and evolution of functional programming in Java, including lambda expressions and streams. It describes how lambda expressions allow passing behaviors as arguments to methods like normal data. This improves API design, opportunities for optimization, and code readability. Streams encourage a lazy, pipelined style and can execute operations in parallel. Functional idioms like immutability and pure functions help enforce correctness and isolation of side effects.
The document discusses the introduction and advantages of lambda expressions and functional programming in Java 8. Some key points include:
- Lambda expressions allow passing behaviors as arguments to methods, simplifying code by removing bulky anonymous class syntax. This enables more powerful and expressive APIs.
- Streams provide a way to process collections of data in a declarative way, leveraging laziness to improve efficiency. Operations can be pipelined for fluent processing.
- Functional programming with immutable data and avoidance of side effects makes code more modular and easier to reason about, enabling optimizations like parallelism. While not natively supported, Java 8 features like lambda expressions facilitate a more functional approach.
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
The document discusses several key concepts in functional programming including:
- Immutable data and pure functions avoid side effects and allow for referential transparency.
- Higher order functions and avoiding mutable state enable concurrency and parallelism without data races.
- Programs can be designed with a pure functional core and push side effects to the outer layers for modularity.
Java 7, 8 & 9 - Moving the language forwardMario Fusco
The document summarizes new features in Java 7-8 including lambda expressions, switch on strings, try-with-resources, and the fork/join framework. Java 8 will focus on lambda expressions to provide functional programming capabilities and default methods to allow interfaces to have default implementations without breaking existing implementations. Java 9 may include additional modularization support.
The document discusses functional programming and lambda expressions in Java 8. It begins by defining functional programming and predicates from predicate logic. It then discusses the key properties of functional programming including no states, passing control, single large function, and no cycles. The document provides examples of determining if a number is prime in both imperative and declarative styles using Java 8 lambda expressions. It also provides examples of getting the first doubled number greater than 3 from a list using both declarative and imperative approaches. The examples demonstrate the use of streams, filters, maps and other functional operations.
This document discusses concurrency, scalability, and fault tolerance using actors and software transactional memory (STM) in Akka. It describes how actors provide message-passing concurrency by isolating processes and avoiding shared state. Actors allow easy reasoning about concurrency by preventing issues like race conditions and deadlocks. The document also covers how Akka implements actors, typed actors, remote actors, supervisor hierarchies for fault tolerance, and STM for coordinating concurrent changes to shared state transactionally. Combining actors with STM results in "transactors" that allow building distributed, concurrent, and fault-tolerant applications.
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Ontico
РИТ++ 2017, AppsConf
Зал Касабланка, 6 июня, 14:00
Тезисы:
http://appsconf.ru/2017/abstracts/2816.html
В докладе рассмотрим цену использования Kotlin в Runtime, обсудим варианты, как улучшить картину мира. Смотреть будем с точки зрения производительности, синхронно углубляясь в особенности Android, а также подумаем, как можно использовать получившийся байткод.
В докладе срыв подкапотных оптимизаций, байткод и цифры, которые покажут, насколько сильно вам смогут помочь все указанные оптимизации.
From object oriented to functional domain modelingMario Fusco
This document discusses moving from an object-oriented approach to a functional approach for domain modeling. It provides examples of modeling a bank account and salary calculator in both OOP and FP styles. Some key benefits of the functional approach highlighted include immutability, avoiding side effects, handling errors through monads instead of exceptions, and composing functions together through currying and composition. Overall the document advocates that while OOP and FP both have merits, modeling as functions can provide advantages in terms of understandability, testability, and extensibility of the code.
OOP and FP - Become a Better ProgrammerMario Fusco
The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8
The Ring programming language version 1.3 book - Part 23 of 88Mahmoud Samir Fayed
This document provides documentation on reflection and meta-programming functions in Ring programming language. Some key functions discussed include locals(), globals(), functions(), cfunctions(), islocal(), isglobal(), isfunction(), iscfunction(), packages(), ispackage(), classes(), isclass(), packageclasses() which allow programmers to retrieve information about variables, functions, packages and classes defined at runtime. Examples are given to demonstrate the usage of each function.
The document contains 21 code snippets showing examples of various Java programming concepts. The code snippets cover topics such as classes and objects, inheritance, interfaces, exceptions, threads, applets, packages, input/output, and networking.
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
- How to adapt to requirement changes using first-class functions
- How you can enhance code reusability using currying
- How you can make your code more robust by favouring immutability over mutability
- How you can design better APIs and reduce unintended null pointer exceptions using an optional data type"
The document contains code snippets for various Java programs that perform tasks like calculating the area of a circle, finding the factorial of a number, displaying prime numbers, sorting an array, counting characters in a string, reversing a string, creating and running threads, handling exceptions, and creating a simple applet with buttons to change the background color. The code examples demonstrate basic Java programming concepts like classes, methods, loops, arrays, exceptions, threads, applets, and event handling.
The Ring programming language version 1.5.2 book - Part 31 of 181Mahmoud Samir Fayed
This document summarizes various functional programming concepts in Ring including pure functions, first-class functions, higher-order functions, anonymous and nested functions, and equality of functions. It also covers reflection and meta-programming capabilities in Ring such as using locals(), globals(), functions(), cfunctions(), islocal(), isglobal(), isfunction(), iscfunction(), packages(), and ispackage() to retrieve and check information about variables, functions, and packages at runtime.
Scala - where objects and functions meetMario Fusco
The document provides an overview of a two-day training course on Scala that covers topics like object orientation, functional programming, pattern matching, generics, traits, case classes, tuples, collections, concurrency, options and monads. The course aims to show how Scala combines object-oriented and functional programming approaches and provides examples of commonly used Scala features like classes, traits, pattern matching, generics and collections.
Introduction to Functional Programming in JavaScripttmont
A presentation I did for work on functional programming. It's meant as an introduction to functional programming, and I implemented the fundamentals of functional programming (Church Numerals, Y-Combinator, etc.) in JavaScript.
The document contains 4 code snippets demonstrating different ways to take input in Java programs:
1) Using command line arguments and the args array to print a greeting with a passed in name
2) Swapping two integers entered from the keyboard using only two variables
3) Reading input from the keyboard using InputStreamReader and BufferedReader classes
4) Taking input using the Scanner class to read an integer, string, and double from console input
The document describes implementing a queue using an array. It provides algorithms for enQueue() and deQueue() operations. EnQueue() inserts elements at the rear by incrementing rear and checking for full. DeQueue() deletes elements from the front by incrementing front and checking for empty. The queue uses front and rear pointers to manage insertion and deletion of elements based on FIFO principle using an underlying fixed-size array.
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
This document summarizes a presentation about functional programming and how functions like map(), flatMap(), and reduce() can simplify collection processing, concurrency, and big data problems. The presentation introduces functional programming concepts and how languages like Java 8 have adopted these with features like lambda expressions and streams. It provides examples of how to use streams to map, filter, and reduce collections in a more declarative way compared to imperative for loops. It also discusses how functions and futures can help simplify concurrent operations by allowing asynchronous work to be expressed more clearly.
The Ring programming language version 1.8 book - Part 37 of 202Mahmoud Samir Fayed
The document discusses various functions in Ring for reflection and meta-programming. It describes functions like locals(), globals(), functions(), cfunctions(), islocal(), isglobal(), isfunction(), iscfunction(), packages(), and others that provide information about variables, functions, packages defined in the runtime environment. These functions allow inspection and modification of the code during execution.
The document discusses functional programming concepts like purity, laziness, immutability, and concurrency. It provides examples using Clojure to illustrate higher order functions like map and filter, immutable data structures, and concurrency in a functional paradigm. The key benefits highlighted are readability, maintainability, avoiding side effects, and easing concurrency through sharing immutable data across threads.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
This document discusses functional programming concepts in JavaScript including imperative vs declarative programming, currying, composition, functors, and the Ramda library. It provides examples of implementing curried functions, function composition, and functors in JavaScript. Functors are discussed in the context of arrays and the Maybe datatype. The Ramda library is presented as an alternative to Underscore/Lodash that follows a more functional programming style with its use of currying and function composition.
The Ring programming language version 1.2 book - Part 21 of 84Mahmoud Samir Fayed
This document summarizes key concepts in functional programming covered in Chapter 35 of the Ring documentation, including pure functions, first-class functions, higher-order functions, anonymous and nested functions, and equality of functions. It provides examples and explanations of each concept.
The document discusses monads and functional programming concepts. It begins by explaining that monads are structures that put values in computational contexts. It then provides a technical definition of a monad involving endofunctors, natural transformations, and laws. Several examples are given to illustrate monads, including the Optional monad in Java to handle null values, and the Stream monad to represent sequences. The document advocates using monads to make aspects like errors, state, and effects explicit in a program's type system.
This document provides an introduction to the Julia programming language. It discusses key features of Julia including its performance similar to C with the readability of Python. Examples show Julia's dynamic type system, array and loop syntax, functions, and support for mathematical operations, conditionals, and Unicode symbols. Special features highlighted are easy parallelization, packaging, and its type system including multiple dispatch and traits.
Pragmatic functional refactoring with java 8 (1)RichardWarburton
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
* How to adapt to requirement changes using first-class functions
* How you can enhance code reusability using currying
* How you can make your code more robust by favouring immutability over mutability
* How you can design better APIs and reduce unintended null pointer exceptions using an optional data type
This document contains code examples demonstrating basic Java concepts like classes, objects, methods, constructors, static variables, and more. The examples show how to define Box classes with width, length and height attributes to calculate and print the volume. Later examples demonstrate method overloading, the use of this keyword, call by value vs reference, and default values of attributes. Constructors are used to initialize object attribute values.
Referential Transparency, Higher Order functions, Lazy Evaluation, and Pattern Matching are key concepts in Functional Programming. Referential Transparency means that equal expressions can be replaced with each other without changing the program's behavior. Higher Order functions allow functions to be passed as arguments to other functions and returned as results. Lazy Evaluation delays evaluating arguments until their values are needed to avoid unnecessary computation. Pattern Matching allows decomposing and analyzing data structures.
The document provides an overview of functional programming in Java. It discusses functional programming concepts like higher-order functions and avoiding side effects. It gives examples of functional-style code in Java for filtering lists and transforming objects. It also discusses how functional programming can be used to implement customizable business logic by passing functions as parameters and looking up functions through a dependency injection container.
From object oriented to functional domain modelingMario Fusco
This document discusses moving from an object-oriented approach to a functional approach for domain modeling. It provides examples of modeling a bank account and salary calculator in both OOP and FP styles. Some key benefits of the functional approach highlighted include immutability, avoiding side effects, handling errors through monads instead of exceptions, and composing functions together through currying and composition. Overall the document advocates that while OOP and FP both have merits, modeling as functions can provide advantages in terms of understandability, testability, and extensibility of the code.
OOP and FP - Become a Better ProgrammerMario Fusco
The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8
The Ring programming language version 1.3 book - Part 23 of 88Mahmoud Samir Fayed
This document provides documentation on reflection and meta-programming functions in Ring programming language. Some key functions discussed include locals(), globals(), functions(), cfunctions(), islocal(), isglobal(), isfunction(), iscfunction(), packages(), ispackage(), classes(), isclass(), packageclasses() which allow programmers to retrieve information about variables, functions, packages and classes defined at runtime. Examples are given to demonstrate the usage of each function.
The document contains 21 code snippets showing examples of various Java programming concepts. The code snippets cover topics such as classes and objects, inheritance, interfaces, exceptions, threads, applets, packages, input/output, and networking.
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
- How to adapt to requirement changes using first-class functions
- How you can enhance code reusability using currying
- How you can make your code more robust by favouring immutability over mutability
- How you can design better APIs and reduce unintended null pointer exceptions using an optional data type"
The document contains code snippets for various Java programs that perform tasks like calculating the area of a circle, finding the factorial of a number, displaying prime numbers, sorting an array, counting characters in a string, reversing a string, creating and running threads, handling exceptions, and creating a simple applet with buttons to change the background color. The code examples demonstrate basic Java programming concepts like classes, methods, loops, arrays, exceptions, threads, applets, and event handling.
The Ring programming language version 1.5.2 book - Part 31 of 181Mahmoud Samir Fayed
This document summarizes various functional programming concepts in Ring including pure functions, first-class functions, higher-order functions, anonymous and nested functions, and equality of functions. It also covers reflection and meta-programming capabilities in Ring such as using locals(), globals(), functions(), cfunctions(), islocal(), isglobal(), isfunction(), iscfunction(), packages(), and ispackage() to retrieve and check information about variables, functions, and packages at runtime.
Scala - where objects and functions meetMario Fusco
The document provides an overview of a two-day training course on Scala that covers topics like object orientation, functional programming, pattern matching, generics, traits, case classes, tuples, collections, concurrency, options and monads. The course aims to show how Scala combines object-oriented and functional programming approaches and provides examples of commonly used Scala features like classes, traits, pattern matching, generics and collections.
Introduction to Functional Programming in JavaScripttmont
A presentation I did for work on functional programming. It's meant as an introduction to functional programming, and I implemented the fundamentals of functional programming (Church Numerals, Y-Combinator, etc.) in JavaScript.
The document contains 4 code snippets demonstrating different ways to take input in Java programs:
1) Using command line arguments and the args array to print a greeting with a passed in name
2) Swapping two integers entered from the keyboard using only two variables
3) Reading input from the keyboard using InputStreamReader and BufferedReader classes
4) Taking input using the Scanner class to read an integer, string, and double from console input
The document describes implementing a queue using an array. It provides algorithms for enQueue() and deQueue() operations. EnQueue() inserts elements at the rear by incrementing rear and checking for full. DeQueue() deletes elements from the front by incrementing front and checking for empty. The queue uses front and rear pointers to manage insertion and deletion of elements based on FIFO principle using an underlying fixed-size array.
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
This document summarizes a presentation about functional programming and how functions like map(), flatMap(), and reduce() can simplify collection processing, concurrency, and big data problems. The presentation introduces functional programming concepts and how languages like Java 8 have adopted these with features like lambda expressions and streams. It provides examples of how to use streams to map, filter, and reduce collections in a more declarative way compared to imperative for loops. It also discusses how functions and futures can help simplify concurrent operations by allowing asynchronous work to be expressed more clearly.
The Ring programming language version 1.8 book - Part 37 of 202Mahmoud Samir Fayed
The document discusses various functions in Ring for reflection and meta-programming. It describes functions like locals(), globals(), functions(), cfunctions(), islocal(), isglobal(), isfunction(), iscfunction(), packages(), and others that provide information about variables, functions, packages defined in the runtime environment. These functions allow inspection and modification of the code during execution.
The document discusses functional programming concepts like purity, laziness, immutability, and concurrency. It provides examples using Clojure to illustrate higher order functions like map and filter, immutable data structures, and concurrency in a functional paradigm. The key benefits highlighted are readability, maintainability, avoiding side effects, and easing concurrency through sharing immutable data across threads.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
This document discusses functional programming concepts in JavaScript including imperative vs declarative programming, currying, composition, functors, and the Ramda library. It provides examples of implementing curried functions, function composition, and functors in JavaScript. Functors are discussed in the context of arrays and the Maybe datatype. The Ramda library is presented as an alternative to Underscore/Lodash that follows a more functional programming style with its use of currying and function composition.
The Ring programming language version 1.2 book - Part 21 of 84Mahmoud Samir Fayed
This document summarizes key concepts in functional programming covered in Chapter 35 of the Ring documentation, including pure functions, first-class functions, higher-order functions, anonymous and nested functions, and equality of functions. It provides examples and explanations of each concept.
The document discusses monads and functional programming concepts. It begins by explaining that monads are structures that put values in computational contexts. It then provides a technical definition of a monad involving endofunctors, natural transformations, and laws. Several examples are given to illustrate monads, including the Optional monad in Java to handle null values, and the Stream monad to represent sequences. The document advocates using monads to make aspects like errors, state, and effects explicit in a program's type system.
This document provides an introduction to the Julia programming language. It discusses key features of Julia including its performance similar to C with the readability of Python. Examples show Julia's dynamic type system, array and loop syntax, functions, and support for mathematical operations, conditionals, and Unicode symbols. Special features highlighted are easy parallelization, packaging, and its type system including multiple dispatch and traits.
Pragmatic functional refactoring with java 8 (1)RichardWarburton
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
* How to adapt to requirement changes using first-class functions
* How you can enhance code reusability using currying
* How you can make your code more robust by favouring immutability over mutability
* How you can design better APIs and reduce unintended null pointer exceptions using an optional data type
This document contains code examples demonstrating basic Java concepts like classes, objects, methods, constructors, static variables, and more. The examples show how to define Box classes with width, length and height attributes to calculate and print the volume. Later examples demonstrate method overloading, the use of this keyword, call by value vs reference, and default values of attributes. Constructors are used to initialize object attribute values.
Referential Transparency, Higher Order functions, Lazy Evaluation, and Pattern Matching are key concepts in Functional Programming. Referential Transparency means that equal expressions can be replaced with each other without changing the program's behavior. Higher Order functions allow functions to be passed as arguments to other functions and returned as results. Lazy Evaluation delays evaluating arguments until their values are needed to avoid unnecessary computation. Pattern Matching allows decomposing and analyzing data structures.
The document provides an overview of functional programming in Java. It discusses functional programming concepts like higher-order functions and avoiding side effects. It gives examples of functional-style code in Java for filtering lists and transforming objects. It also discusses how functional programming can be used to implement customizable business logic by passing functions as parameters and looking up functions through a dependency injection container.
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 functions in C programming. It covers defining and declaring functions, variable scope, parameter passing, inline functions, recursive functions, function arguments, and function applications. It provides examples of function definitions and calls using integers, strings, and arrays. It explains call by value, call by address, and call by reference parameter passing. It also discusses global, private, and static variables and using the scope resolution operator.
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.
This document provides an overview of Java 8 lambda expressions. It begins with an introduction and background on anonymous classes in previous Java versions. The main topics covered include lambda syntax, lambda expressions vs closures, capturing variables in lambda expressions, type inference, and functional interfaces. It also discusses stream operations like filter, map, flatMap, and peek. Finally, it covers parallelism and how streams can leverage multiple cores to improve performance.
The document is a report on the topic of computer programming and utilization prepared by group C. It discusses functions, including the definition of a function, function examples, benefits of functions, function prototypes, function arguments, and recursion. It provides examples of math library functions, global and local variables, and external variables. It also includes examples of recursive functions to calculate factorials and the Fibonacci series recursively.
What's in Kotlin for us - Alexandre Greschon, MyHeritageDroidConTLV
The document discusses Kotlin for Android development. It provides an overview of Kotlin, explaining that it is a programming language created by JetBrains that is now adopted by Google for Android. It highlights some key features of Kotlin like being concise, interoperable with Java, and adding null safety to the type system. The rest of the agenda covers topics like Android Kotlin extensions, functions, classes, and a glimpse at the future of Kotlin.
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
This document provides an overview of functional programming concepts for object-oriented programmers. It discusses the fundamentals of FP including immutability, purity, first-class and higher-order functions, closures, and recursion. It provides examples of these concepts in languages like Lisp, F#, C#, and JavaScript. The document also compares OO and FP concepts and discusses derived FP concepts like partial application, lazy evaluation, and pattern matching.
The document provides an overview of functional programming concepts including:
- Functions are the primary building blocks and avoid side effects by being pure and using immutable data.
- Referential transparency means functions always return the same output for a given input.
- Higher order functions accept or return other functions. Function composition combines functions.
- Partial application and currying transform functions to accept arguments incrementally.
Java 8 introduced several new features including lambda expressions, which allow functional-style programming in Java through functional interfaces containing a single abstract method, streams, which provide a way to process collections of objects in a declarative way, and default and static methods in interfaces to enable multiple inheritance. The document provides examples of using these new Java 8 features such as lambda expressions, functional interfaces, streams, and default and static methods in interfaces.
This document discusses JavaScript functions. It explains that functions are first-class objects that can be stored in variables, passed as arguments, and returned from other functions. It provides examples of defining, calling, and returning values from functions. It also covers optional parameters, anonymous functions, higher-order functions, and functions as methods.
This document provides a summary of new features in JavaScript, including let/const block scoping, arrow functions, template strings, classes, generators, async/await, and more. It explains each feature in 1-3 sentences and includes code examples.
This document discusses JavaScript functions. It covers function definitions, invocation patterns, the this keyword, and function methods like call, apply, and bind. Function definitions can be declared using the function keyword or assigned anonymously. Functions are first-class citizens that can be passed around and returned. Invocation patterns include direct invocation, method invocation, constructor invocation, and reflective invocation using call and apply. The this keyword is determined by the invocation pattern and bind can be used to set the this value.
Я расскажу о нестандартных особенностях языка для реальных проектов. Речь пойдет о том, зачем усложнять себе жизнь и какие преимущества это может дать.
- Protocol-Oriented Programming и его дилеммы
- Когда и зачем использовать обобщения и вложенные типы
- Настоящее и будущее Swift
Александр Зимин (Alexander Zimin) — Магия SwiftCocoaHeads
Александр говорил о нестандартных особенностях языка для реальных проектов. О том, зачем усложнять себе жизнь и какие преимущества это может дать.
- Protocol-Oriented Programming и его дилеммы
- Когда и зачем использовать обобщения и вложенные типы
- Настоящее и будущее Swift
The document discusses reactive programming and how it can be used on Android. It explains that reactive programming uses observable sequences and asynchronous data flows. It introduces RxJava as a library for reactive programming that uses Observables to compose flows of asynchronous data. It provides examples of how RxJava can be used on Android to perform background tasks, handle errors and activity lifecycles, load images asynchronously, and create and transform Observables.
Building Production Ready Search Pipelines with Spark and MilvusZilliz
Spark is the widely used ETL tool for processing, indexing and ingesting data to serving stack for search. Milvus is the production-ready open-source vector database. In this talk we will show how to use Spark to process unstructured data to extract vector representations, and push the vectors to Milvus vector database for search serving.
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...alexjohnson7307
Predictive maintenance is a proactive approach that anticipates equipment failures before they happen. At the forefront of this innovative strategy is Artificial Intelligence (AI), which brings unprecedented precision and efficiency. AI in predictive maintenance is transforming industries by reducing downtime, minimizing costs, and enhancing productivity.
This presentation provides valuable insights into effective cost-saving techniques on AWS. Learn how to optimize your AWS resources by rightsizing, increasing elasticity, picking the right storage class, and choosing the best pricing model. Additionally, discover essential governance mechanisms to ensure continuous cost efficiency. Whether you are new to AWS or an experienced user, this presentation provides clear and practical tips to help you reduce your cloud costs and get the most out of your budget.
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
5th LF Energy Power Grid Model Meet-up SlidesDanBrown980551
5th Power Grid Model Meet-up
It is with great pleasure that we extend to you an invitation to the 5th Power Grid Model Meet-up, scheduled for 6th June 2024. This event will adopt a hybrid format, allowing participants to join us either through an online Mircosoft Teams session or in person at TU/e located at Den Dolech 2, Eindhoven, Netherlands. The meet-up will be hosted by Eindhoven University of Technology (TU/e), a research university specializing in engineering science & technology.
Power Grid Model
The global energy transition is placing new and unprecedented demands on Distribution System Operators (DSOs). Alongside upgrades to grid capacity, processes such as digitization, capacity optimization, and congestion management are becoming vital for delivering reliable services.
Power Grid Model is an open source project from Linux Foundation Energy and provides a calculation engine that is increasingly essential for DSOs. It offers a standards-based foundation enabling real-time power systems analysis, simulations of electrical power grids, and sophisticated what-if analysis. In addition, it enables in-depth studies and analysis of the electrical power grid’s behavior and performance. This comprehensive model incorporates essential factors such as power generation capacity, electrical losses, voltage levels, power flows, and system stability.
Power Grid Model is currently being applied in a wide variety of use cases, including grid planning, expansion, reliability, and congestion studies. It can also help in analyzing the impact of renewable energy integration, assessing the effects of disturbances or faults, and developing strategies for grid control and optimization.
What to expect
For the upcoming meetup we are organizing, we have an exciting lineup of activities planned:
-Insightful presentations covering two practical applications of the Power Grid Model.
-An update on the latest advancements in Power Grid -Model technology during the first and second quarters of 2024.
-An interactive brainstorming session to discuss and propose new feature requests.
-An opportunity to connect with fellow Power Grid Model enthusiasts and users.
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on automated letter generation for Bonterra Impact Management using Google Workspace or Microsoft 365.
Interested in deploying letter generation automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfChart Kalyan
A Mix Chart displays historical data of numbers in a graphical or tabular form. The Kalyan Rajdhani Mix Chart specifically shows the results of a sequence of numbers over different periods.
Main news related to the CCS TSI 2023 (2023/1695)Jakub Marek
An English 🇬🇧 translation of a presentation to the speech I gave about the main changes brought by CCS TSI 2023 at the biggest Czech conference on Communications and signalling systems on Railways, which was held in Clarion Hotel Olomouc from 7th to 9th November 2023 (konferenceszt.cz). Attended by around 500 participants and 200 on-line followers.
The original Czech 🇨🇿 version of the presentation can be found here: https://www.slideshare.net/slideshow/hlavni-novinky-souvisejici-s-ccs-tsi-2023-2023-1695/269688092 .
The videorecording (in Czech) from the presentation is available here: https://youtu.be/WzjJWm4IyPk?si=SImb06tuXGb30BEH .
A Comprehensive Guide to DeFi Development Services in 2024Intelisync
DeFi represents a paradigm shift in the financial industry. Instead of relying on traditional, centralized institutions like banks, DeFi leverages blockchain technology to create a decentralized network of financial services. This means that financial transactions can occur directly between parties, without intermediaries, using smart contracts on platforms like Ethereum.
In 2024, we are witnessing an explosion of new DeFi projects and protocols, each pushing the boundaries of what’s possible in finance.
In summary, DeFi in 2024 is not just a trend; it’s a revolution that democratizes finance, enhances security and transparency, and fosters continuous innovation. As we proceed through this presentation, we'll explore the various components and services of DeFi in detail, shedding light on how they are transforming the financial landscape.
At Intelisync, we specialize in providing comprehensive DeFi development services tailored to meet the unique needs of our clients. From smart contract development to dApp creation and security audits, we ensure that your DeFi project is built with innovation, security, and scalability in mind. Trust Intelisync to guide you through the intricate landscape of decentralized finance and unlock the full potential of blockchain technology.
Ready to take your DeFi project to the next level? Partner with Intelisync for expert DeFi development services today!
Best 20 SEO Techniques To Improve Website Visibility In SERPPixlogix Infotech
Boost your website's visibility with proven SEO techniques! Our latest blog dives into essential strategies to enhance your online presence, increase traffic, and rank higher on search engines. From keyword optimization to quality content creation, learn how to make your site stand out in the crowded digital landscape. Discover actionable tips and expert insights to elevate your SEO game.
Digital Marketing Trends in 2024 | Guide for Staying AheadWask
https://www.wask.co/ebooks/digital-marketing-trends-in-2024
Feeling lost in the digital marketing whirlwind of 2024? Technology is changing, consumer habits are evolving, and staying ahead of the curve feels like a never-ending pursuit. This e-book is your compass. Dive into actionable insights to handle the complexities of modern marketing. From hyper-personalization to the power of user-generated content, learn how to build long-term relationships with your audience and unlock the secrets to success in the ever-shifting digital landscape.
Trusted Execution Environment for Decentralized Process MiningLucaBarbaro3
Presentation of the paper "Trusted Execution Environment for Decentralized Process Mining" given during the CAiSE 2024 Conference in Cyprus on June 7, 2024.
Monitoring and Managing Anomaly Detection on OpenShift.pdfTosin Akinosho
Monitoring and Managing Anomaly Detection on OpenShift
Overview
Dive into the world of anomaly detection on edge devices with our comprehensive hands-on tutorial. This SlideShare presentation will guide you through the entire process, from data collection and model training to edge deployment and real-time monitoring. Perfect for those looking to implement robust anomaly detection systems on resource-constrained IoT/edge devices.
Key Topics Covered
1. Introduction to Anomaly Detection
- Understand the fundamentals of anomaly detection and its importance in identifying unusual behavior or failures in systems.
2. Understanding Edge (IoT)
- Learn about edge computing and IoT, and how they enable real-time data processing and decision-making at the source.
3. What is ArgoCD?
- Discover ArgoCD, a declarative, GitOps continuous delivery tool for Kubernetes, and its role in deploying applications on edge devices.
4. Deployment Using ArgoCD for Edge Devices
- Step-by-step guide on deploying anomaly detection models on edge devices using ArgoCD.
5. Introduction to Apache Kafka and S3
- Explore Apache Kafka for real-time data streaming and Amazon S3 for scalable storage solutions.
6. Viewing Kafka Messages in the Data Lake
- Learn how to view and analyze Kafka messages stored in a data lake for better insights.
7. What is Prometheus?
- Get to know Prometheus, an open-source monitoring and alerting toolkit, and its application in monitoring edge devices.
8. Monitoring Application Metrics with Prometheus
- Detailed instructions on setting up Prometheus to monitor the performance and health of your anomaly detection system.
9. What is Camel K?
- Introduction to Camel K, a lightweight integration framework built on Apache Camel, designed for Kubernetes.
10. Configuring Camel K Integrations for Data Pipelines
- Learn how to configure Camel K for seamless data pipeline integrations in your anomaly detection workflow.
11. What is a Jupyter Notebook?
- Overview of Jupyter Notebooks, an open-source web application for creating and sharing documents with live code, equations, visualizations, and narrative text.
12. Jupyter Notebooks with Code Examples
- Hands-on examples and code snippets in Jupyter Notebooks to help you implement and test anomaly detection models.
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Is java8a truefunctionallanguage
1. IS JAVA 8 A TRUE FUNCTIONAL PROGRAMMING LANGUAGE ?
- Samir Chekkal
- Saad El Khlifi
2. Plan
1. Programming Paradigm Overview
2. Imperative Pardigm Vs Functional Paradigm
3. Corner Stones of Functional Paradigm
1. Immutablity
2. Recursion
3. Functions as first class citizens
4. Higher order functions
5. Lazyness
4. Conclusion
3. 1.Programming Paradigm Overview
- A programming paradigm is a general approach, orientation, or philosophy
of programming that can be used when implementing a program.
- Main programming paradigms:
- Imperative programming: C, Java, Scala ...
- Functionnal programming: Haskell, ML, Scala, Java 8 (?) ...
- Logic programming: Prolog ...
- Object Oriented Programming: Java, Scala, ...
4. 2.Imperative Pardigm Vs Functional Paradigm
static List<String> approvisionnement() {
List<String> refs = new ArrayList<>();
int index = 0;
for(Product p : Store.catalog()) {
if(p.getCategory() == Product.Category.MOBILE_PHONE) {
refs.add(p.getRef());
index ++;
if(index > 10)
break;
}
}
Collections.sort(refs);
return refs;
}
5. 2.Imperative Pardigm Vs Functional Paradigm
static Map<Product.Category, List<Product>> categories() {
Map<Product.Category, List<Product>> result = new HashMap<>();
for(Product p : Store.catalog()) {
if(result.get(p.getCategory()) != null) {
result.get(p.getCategory()).add(p);
} else {
List<String> catProducts = new ArrayList<>();
catProducts.add(p);
result.put(p.getCategory(), catProducts);
}
}
return result;
}
8. 3. Corner Stones of Functional Paradigm
1. Immutablity
2. Recursion
3. Functions as first class citizens
4. Higher order functions
5. Lazyness
9. 3.1 Immutablity
- High level coding
- Mutability + Shared state = Time
bomb
- Parallelism
- But Threads API is complexe
- For free with streams! Really ?
10. static long badIdea() {
// Tables are not thread safe:
// Correctness ?
long[] acc = {0L};
LongStream
.rangeClosed(1, LIMIT)
.parallel()
.forEach( i -> acc[0] += i);
return acc[0];
}
static long lessBadIdea() {
// Thread safe , correct response
// Performance ?
AtomicLong acc = new AtomicLong(0L);
LongStream
.rangeClosed(1, LIMIT)
.parallel()
.forEach( i -> acc.addAndGet(i));
return acc.get();
}
static long sumByReduction() {
return LongStream
.rangeClosed(1, LIMIT)
.parallel()
.sum();
}
3.1 Immutablity
Result: 5000000050000000
in ~288 ms
Result: 5000000050000000
in ~8306 ms
Result: 1839299186097435
in ~342 ms
11. 3.2.Recursion
static long factorialImperative(final int n) {
long r = 1;
for (int i = 1; i <= n; i++) {
r *= i;
}
return r;
}
static long recFact(final long n) {
return (n == 1) ? 1 : n*recFact(n-1);
}
13. 3.2.Recursion
static long factorialTailRecursive(final long n) {
return factorialHelper(n, 1);
}
private static long factorialHelper(final long n, final long acc) {
return n == 1 ? acc : factorialHelper(n-1, n*acc);
}
20. 3.3.First class functions
java.util.function package to the rescue
• Predicate
• Consumer
• Supplier
• Function
• …
21. 3.4.Higher order functions
static int sumOfInts(int a, int b) {
return a > b ? 0 : a + sumOfInts(a+1, b);
}
static int sumOfCubes(int a, int b) {
return a > b ? 0 : a*a*a + sumOfCubes(a+1, b);
}
static int sumOfFact(int a, int b) {
return a > b ? 0 : fact(a) + sumOfFact(a+1, b)
}
22. 3.4.Higher order functions
static int higherSum(Function<Integer, Integer> f, int a, int b) {
return a > b ? 0 : f.apply(a) + higherSum(f, a + 1, b);
}
int sumOfSquare = higherSum(x->x*x, 1, 6);
int sumOfCube = higherSum(x->x*x*x, 5, 21);
int sumOfFactoriel = higherSum(x->fact(x), 13, 17);
…..
23. 3.4.Higher order functions
static BiFunction<Integer, Integer, Integer> curriedSum(Function<Integer, Integer> f) {
return
(a, b) -> { return a > b ? 0 : f.apply(a) + curriedSum(f).apply(a+1, b); };
}
// Curryed version call
int sumOfSquare = curriedSum(x->x*x).apply(1, 6);
int sumOfCube = curriedSum(x->x*x*x).apply(5, 21);
int sumOfFactoriel = curriedSum(x->fact(x)).apply(13, 17);
…..
28. References
- http://clojure.org/rationale Mutable stateful objects are the new spaghetti code
- Compositional Programming: http://www.cs.ox.ac.uk/research/pdt/ap/ssgp/slides/odersky.pdf
- http://www.info.ucl.ac.be/~pvr/paradigmsDIAGRAMeng108.pdf
- http://www.ibm.com/developerworks/aix/library/au-aix-multicore-multiprocessor/
Editor's Notes
Merci d’être venu pour assister à cette session
Merci à JMaghreb pour cette exellente occasion qu’on nous a donné à fin de nous permettre nous exprimer sur un des sujet qui nous est cher qui est la pro
…. Je m’appelle Saad El Khlif, .. Je suis Developpeur Java chez SQLi
Et voici mon collègue que je lui laisserais le soin de se présenter …..
Comme tout le monde sait aujourd’hui le langage Java avec sa nouvelle version Java 8 a apporté avec lui de nouvelle features, avec un des plus grand changement qu’a connu le langage depuis sa version 5, et cela avec comme objectif principale : Embrasser le monde fonctionnelle, tout le monde maintenant a sans doute entendu parler des Lambda expressions, des interfaces fonctionnelles, des streams...etc
Très bien .
Alors aujourd’hui nous allons vous parler des principaux concepts qui caractérisent la programmation fonctionnelle et surtout nous allons essayer de projeter Java 8 sur ces concepts et cela pour savoir à quel point Java 8, se considère comme langage fonctionnel, est ce que Java 8 est un vrai langage fonctionnel ? c’est ça la question que nous allons essayer à travers cette session analyser et répondre !
d’abord c’est quoi la programmation fonctionnelle ?
Qu’apporte ce paradigme de programmation en terme de mécanisme, d’idioms, capables de nous aider nous développeurs à construire des logiciels rebuste, flexible, facilement maintenable, et avec un grand niveau de reutilisabilité ?
Tout ça et autres font le menu de cette session !
Dans cette session nous allons dans un premier lui (lieu) rappeller les différents paradigmes de programmation
Pour cela nous allons revenir sur la définition de ce que s’est que un paradigme
après nous allons essyer d’enumerer l’ensemble des principaux paradigmes les plus influents et les plus utilisés aujourd’hui
Une fois c’est fait nous allons essayer d’attaquer le paradigme fonctionnelle avec les différent concepts et mécanismes qui les caractérise
Et à la fin nous allons conclure et laisser le temps pour les questions réponses
Comme vous le remarquez Java se situe un peu partout, il est considéré maintenant de plus en plus un langage polyvalent
A noter que Java avant la version d’aujourd’hui la 8, on pouvait faire avec de la programmation fonctionnelle. mais, et nous allons le constater ensemble,
il n’était pas adapté pour jouer ce rôle, c’est à dire, Java 7 et inférieur ne disposait pas des mécanismes forts pour le qualifier dans le rang des langages fonctionnelles
Vous allez voir que le paradigme fonctionnelle est un style complètement à part ce que nous avons l’habitude de faire dans nos développement de tous les jours. c’est un style qui pour l’adopter il faut non seulement une nouvelle façon de voir les choses mais aussi faut les mécanismes nécessaire capables de le rendre applicable.
Pour donner une définition claire du style de la programmation fonctionnelle, permettez nous de vous exposer un exemple de plain old java code
Par-contre nous allons demander à vous de le lire , l'expliquer et le qualifier,, et comme nous avons que peu temps, le challenge sera de le lire dans 10 seconde ?
…
…
Il s’agit d’une fonction qui sert à retourner la liste triée de 10 références de produits de type MOBILE_PHONE, l’objectif et d’approvisionner le stock
C’est un besoin qui comme vous venez de le constater facile à exprimer mais un peu complexe à coder, à lire, maintenir.. etc
Pour vous rapprocher encore plus de l’idée, permettez nous de vous donner un deuxième exemple, et vous demander encore une fois de le lire, l’expliquer et le qualifier.
Il s’agit d’une fonction ayant pour objectif de retourner le liste des produits par groupés par category (c’est comme une requête groupeBy de SQL que nous avons l’habitude de manipuler)
Encore une fois c’est une fonctionnalité facile à exprimer, mais, avec le code que nous avons l’habitude d'écrire est un code difficile à lire, bas niveau
Au lieu d’exprimer facilement notre besoin on est obliger d’exprimer le comment, les étapes à suivre pour arriver à ce que nous voulons
De plus avouons le c’est un code verbeux , nous avons beaucoup de variable à déclarer et a manipuler, des structure de contrôle
deux exemples
Les deux bout de code que nous venons de vous présenter représentent le paradigme impératif
un ensemble d’instruction de bas niveaux ayant pour objectif de basculer d’un état à un autre
mutabilité, side effect, itération avec des boucle sont les caractéristiques de la programmation impératif
Très bien
Maintenant nous péremétez nous de vous présenter un autre extrait de code et vous demander de le lire
N’essayez pas de vous vous perturber avec ce que ça veut dire le mot stream
Essayez de lire le code de la manière la plus naturelle possible, essayez le lire les verbes
Comme vous venez de le constater c’est un code qui ressemble exactement à l'énoncez du problème
Une seule ligne de code de haut niveau, concis, facile à lire, et à évoluer
Pas de variable et créer et à manipuler, pas de boucle à gérer,
Les verbe sont des fonctions
Vous allez nous dire , on connaît tous ce que c’est que une fonction, mais comment on fait à fin de pouvoir les composer d’une façon aussi élégante comme dans la code ??
Avant de vous répondre
Permettez moi de revenir sur le deuxième problème et de vous proposer une deuxième version :)
Encore une fois ; une seule ligne de code concis qui représente exactement l’expression du besoin.
Supposons que demain le besoin change, on veut plus les produits mais uniquement leurs références groupé par category
Pour s’adapter avec cette nouvelle demande, dans la version précédente, il faut avoir une maîtrise complète du code
il faut être très prudent pour ne pas introduire des bugs
Avec la nouvelle version , c’est toutjours dans une seule ligne , nous avons compris qu’il s’agit d’un mapping du produit sur sa réference
Il suffit d’exprimer ça.
Code de haut niveau, un code qu’on puisse lire comme une histoire, et pas comme un puzzle, un code déclarative
Pas de variables à mutter et à manipuler, Flexiblité, facile adapatation au changement,
une composition de fonctions
Tels sont les caractéristiques de la programmation fonctionnelle
Maintenant que nous avons pu souligner ensemble le style qui définit la programmation fonctionnelle, et ayant tous compris la différence par rapport
à la programmation impérative
nous allons dans cette partie de la session essayer de vous présenter les principaux mécanisme sur lesquels se base la programmation fonctionnelles
Autrement les mécanismes qui vont rendre ce style de programmation possible.
Étant donnée que le style de programmation fonctionnel donne une grande importance a l'immutabilité, les structures de contrôle classiques (tel que for, while, do … while) n’ont pas de place dans ce paradigme car implicitement la condition d'arrêt de ces boucles nécessite le test sur une variable dont l'état doit être modifié sinon on aura une boucle infini.
Face a ce dilemme on a recours a la récursivité ou plus précisément les fonctions récursives.
Une fonction récursive est tous simplement une fonction qui fait appel a elle même.
Vous allez me dire, oui on est tous conscient du concept des fonctions récursives mais on ne les utilises pas car une fonction récursive est plus lente que son équivalente itérative (on utilisant des boucles classiques). Mais ceci n’est pas un défaut inhérent à récursivité, mais un manque de support de ce concept dans le langage de programmation qu’on utilise (Java est bien sur concerne par ce manque).
Pour illustrer ceci, considérant l’exemple simple du calcul du factoriel d’un nombre entier donne.
La définition mathématique du factoriel est simplement:
le factoriel de 1 est 1
le factoriel d’un nombre n supérieur a 1 est égal a: n fois le factoriel de (n-1)
Dans Java on peut implémenté cette fonction de deux manières: itérative ou récursive.
Pour la fonction itérative factorialImperative, elle utilise la mutabilité de la variable locale r en plus d’une boucle for pour calculer le résultat.
Considérant maintenant l’autre définition récursive, elle mirror (reprend) exactement la définition mathématique du factoriel et se lis simplement: Si le nombre entré est 1 le résultat est 1 sinon on multiplie le nombre par factoriel du nombre juste avant.
On constate que le code récursive est d’un niveau d’abstraction plus élevé, il n’y a pas de changement d'état et on peut le lire comme une histoire, en contraste dans le code itératif on doit faire plus d’effort mental : suivre l'évolution de la variable local, vérifié si les conditions d'arrêt de la loupe sont correctes, en plus la solution iterative n’a aucune relation avec la définition de l’enonce initial (on doit faire plus d’effort pour arriver a la solution impérative que son contre part récursive).
Normalement on doit avoir la liberté de choisir le style de fonction (itérative ou récursive) le plus adapte au probleme en question.
Mais pourquoi dans Java (et autre langages impératifs) on a tendance a éviter les fonctions récursives, tout simplement car la solution s'avère moins performante qu’une solution itérative.
La solution récursive n’est pas optimal même dans un langage fonctionnel, tous simplement on aura une explosion du stack pour les grand nombre, car on continue a empiler les résultats intermédiaires n’effectuant la multiplication que lorsqu’on arrive au cas de base (dans ce cas le nombre 1).
Considérant par exemple le calcul du factorial de 5:
La forme de cette exécution est caractérisée par une expansion (ou le stack ne fait que grandir: appels recursives) et ensuite une contraction (on combine les resultats intermidiaires)
Pour éviter l’accumulation des résultats intermédiaires on a recours a l’utilisation d’un accumulateur, tous simplement un accumulateur est un paramètre additionnel qu’on passe a la fonction est qui contient le résultat final des appels précèdents.
On réécrit alors la définition de notre fonction récursive en utilisant l’accumulateur, la fonction utilitaire factorialHelper prends en plus du nombre n, un autre nombre acc, et dans son appel récursif a elle même elle multiplie l’ancien accumulateur par le nombre en question, decremente n et passe ces deux parametres pour le prochain appel recursif.
Voyans maintenat l’execution de cette fonction:
Dans cette exécution on vois que le stack n’augmente pas, les résultats intermédiaires sont passes dans le deuxième paramètre.
Un point fort des langage fonctionnel est qu’il peuvent détecter cette optimisation et le code générer et équivalent a une solution itérative n’augmentant pas la taille pour empiler les appels récursifs inutilement. Cette technique est appelée “call-tail optimisation”.
Malheureusement cette technique n’est pas supporter par le langage Java.
Avant Java 8, les fonctions été considérées comme des citoyens de seconds rond. Il est bien évident que l’on été conscient de l’importance que jouent les fonctions; en tous cas c’est les fonctions qui font tous le travail, les objets sert a les regrouper et réduire leur visibilité.
Meme avec Java 8, on n’a toujours pas la notion de function-literal, on est oblige de passer par des interfaces.
Pré Java 8, on peut implémenter cette logique en passant par une instance d’une classe anonyme.
Considérons deux exemples:
Dans le premier cas on crée un Thread qui va afficher “Hello World” lors de son exécution
Dans le second exemple on associe une call-back qui affichera le message “Button Pressed” lorsqu’on click sur le boutton
Dans ces deux exemple ce qu’on veux exécuter est simple (le code en vert) mais on se trouve obligé de mettre notre code dans des templates qui n’ajoute aucune valeur a notre code. (c’est ce que le professor Venkat Subramaniam appele ceremonie).
Heureusement Java8 a pris conscience qu’elle doit enfin éliminer cette façon tordu et verbeuse, meme si avec support limite (on a tjr pas la notion des function literal) en introduisant les expressions lambda aussi appele fonctions anonymes.
Proposition: Les fonctions servent à abstraire un comportement pour la réalisation d’un traitement, c’est le mécanisme le plus important dans un langage de programmation car avec on peut créer le coeur du process et sans lui on peut rien faire.
le fait que ce traitement soit parametrizable, pour qu’on puisse les passer dans les parametres , le retourner, les instancier comme une valeur, comme toute autre valeur (int, enum, object...) on était obligé de le wrapper dans un objet => verbosité
L’idiom qui consiste à factoriser un comportement commun (comme ce que venons de voir avec l’API stream) et le passer en paramètre ne pouvait pas se fait sans cette opération qui consiste à wrapper ce comportement dans un objet.
Toute entité ayant cette possiblité d’être déclaré et instancité, et capable de passer en parametre et etre retourné comme résultat, est concidéré uen entité de premiere classe
(en orienté objet et java actuellement
les fonctions sont soit des méthodes statiques, soit des méthodes membres d’objets, dans le premier cas
il s’agit des fonction utilitaires factorisant un traitement commain qu’on appelle dans notre code pour éviter la répitition
Mais impossible de les passer comme paramètre ...)
Cette solution est nomme “lambda expression” ou “fonction anonyme”.
On peut facilement adapter notre ancien style d’utilisation des classes anonymes pour utiliser les expressions lambda simplement par supprimession du code inutile, (code bare en rouge, les parentheses sont optionel si on a une seule ligne) et ajouter une fleche entre le tuple representant les arguments et le core du traitement.
Voici la version final de ces deux exemples après élimination du code inutile.
Le deux lignes font exactement la même chose que ce qu’on pouvait avant réaliser avec les classes anonymes, et comme cerise sur le gâteau le compilateur est maintenant capable d'inférer le type du paramètre e en tant que ActionEvent.
En fait on est pas obliger de renseigner le type des paramètres des fonctions anonymes.
Dans le cas ou on veut utiliser une méthode déjà existante, on peut utiliser le “Pattern Adapter”, on va créer une autre classe qui implémente l’interface attendue, et dans son implementation on va déléguer les traitements vers une instance privée de la classe ayant déjà la fonction qu’on veut réutiliser). Ou créer une classe anonyme qui fait appel a la methode, heureusement Java 8 a introduite la notion de méthodes références.
Une restriction importante des expressions lambda, c’est que l’interface a laquelle s’attend le client (Target Type), doit avoir une seule méthode abstraite. C’est ce qu’on appel interface SAM (Single Abstract Method), on peut avoir d’autre méthodes dans l'interface mais pour ces méthode on doit fournir une implementation. Oui avec Java 8 on peut implémenter des méthodes ce qu’on appel default methodes.
C’est grâce au Single Abstract Method interface que le compilateur Java 8 est capable de créer une implementation de l’interface attendue et d'inférer les type des parametres.
Une autre restriction des expressions lambda c’est qu’on ne peut les affecter qu’au variable de type SAM interface dont la seule méthode non implémenté est coherente avec la signature du lambda. On ne peut pas affecter une lambda même a une variable de type objet.
Vue l’obligation que la signature de la méthode lambda doit être cohérente avec la signature d’une interface donnée, et pour ne pas obliger les développeur a créer une interface appropriée a chaque fois qu’il veut utiliser une fonction anonyme. le package java.util.function offre plusieurs SAM interfaces adaptées a plusieurs circonstances, on trouve par exemple:
- Predicate
Consumer: pour toute lambda expression qui prend un paramètre et n retourne aucune valeure
Supplier : Pour tout lambda expression qui ne prend aucun paramètre et retourne une valeure
Function: Prend un paramètre et retourne une valeur
….
Selon votre cas d’utilisation vous avez a choisir l’interface SAM qui repond le mieux a votre besoin.
Dans le cas ou on veut utiliser une méthode déjà existante, on peut utiliser le “Pattern Adapter”, on va créer une autre classe qui implémente l’interface attendue, et dans son implementation on va déléguer les traitements vers une instance privée de la classe ayant déjà la fonction qu’on veut réutiliser). Ou créer une classe anonyme qui fait appel a la methode, heureusement Java 8 a introduite la notion de méthodes références.
Une restriction importante des expressions lambda, c’est que l’interface a laquelle s’attend le client (Target Type), doit avoir une seule méthode abstraite. C’est ce qu’on appel interface SAM (Single Abstract Method), on peut avoir d’autre méthodes dans l'interface mais pour ces méthode on doit fournir une implementation. Oui avec Java 8 on peut implémenter des méthodes ce qu’on appel default methodes.
C’est grâce au Single Abstract Method interface que le compilateur Java 8 est capable de créer une implementation de l’interface attendue et d'inférer les type des parametres.
Une autre restriction des expressions lambda c’est qu’on ne peut les affecter qu’au variable de type SAM interface dont la seule méthode non implémenté est coherente avec la signature du lambda. On ne peut pas affecter une lambda même a une variable de type objet.
Vue l’obligation que la signature de la méthode lambda doit être cohérente avec la signature d’une interface donnée, et pour ne pas obliger les développeur a créer une interface appropriée a chaque fois qu’il veut utiliser une fonction anonyme. le package java.util.function offre plusieurs SAM interfaces adaptées a plusieurs circonstances, on trouve par exemple:
- Predicate
Consumer: pour toute lambda expression qui prend un paramètre et n retourne aucune valeure
Supplier : Pour tout lambda expression qui ne prend aucun paramètre et retourne une valeure
Function: Prend un paramètre et retourne une valeur
….
Selon votre cas d’utilisation vous avez a choisir l’interface SAM qui repond le mieux a votre besoin.
Dans le cas ou on veut utiliser une méthode déjà existante, on peut utiliser le “Pattern Adapter”, on va créer une autre classe qui implémente l’interface attendue, et dans son implementation on va déléguer les traitements vers une instance privée de la classe ayant déjà la fonction qu’on veut réutiliser). Ou créer une classe anonyme qui fait appel a la methode, heureusement Java 8 a introduite la notion de méthodes références.
Une restriction importante des expressions lambda, c’est que l’interface a laquelle s’attend le client (Target Type), doit avoir une seule méthode abstraite. C’est ce qu’on appel interface SAM (Single Abstract Method), on peut avoir d’autre méthodes dans l'interface mais pour ces méthode on doit fournir une implementation. Oui avec Java 8 on peut implémenter des méthodes ce qu’on appel default methodes.
C’est grâce au Single Abstract Method interface que le compilateur Java 8 est capable de créer une implementation de l’interface attendue et d'inférer les type des parametres.
Une autre restriction des expressions lambda c’est qu’on ne peut les affecter qu’au variable de type SAM interface dont la seule méthode non implémenté est coherente avec la signature du lambda. On ne peut pas affecter une lambda même a une variable de type objet.
Vue l’obligation que la signature de la méthode lambda doit être cohérente avec la signature d’une interface donnée, et pour ne pas obliger les développeur a créer une interface appropriée a chaque fois qu’il veut utiliser une fonction anonyme. le package java.util.function offre plusieurs SAM interfaces adaptées a plusieurs circonstances, on trouve par exemple:
- Predicate
Consumer: pour toute lambda expression qui prend un paramètre et n retourne aucune valeure
Supplier : Pour tout lambda expression qui ne prend aucun paramètre et retourne une valeure
Function: Prend un paramètre et retourne une valeur
….
Selon votre cas d’utilisation vous avez a choisir l’interface SAM qui repond le mieux a votre besoin.
On arrive maintenant au mécanisme d'abstraction (et de composition) le plus utiliser dans les langages fonctionnels, et ce des fonctions de haut niveau (HOF).
Une fonction de haut niveau est simplement une fonction qui prend des fonction en tant que paramètre ou retourne une fonction en tant que resultat.
Le concept des HOF nous permet d'implémenter facilement le pattern Strategy (ou ce qu’est aussi appelé parametrisation du comportement).
Considérant les trois exemples suivants:
On a une fonction pour le calcul de la somme des entiers entre un interval a et b
La deuxieme fonction consiste elle a calculer la somme des cube des entier entre un interval a et b
La troisieme fonction calcul la somme des factoriels des entiers entre a et b
Les trois fonctions sont récursives et on n’a pas utiliser le cumulateur pour TCO, pour simplifier les exemples.
On voit que la forme des trois fonctions est semblable, elle diffèrent uniquement au niveau du code colore en rouge. Pour unifier ces trois fonctions on a recours au Design Pattern Strategy dans la terminologie des langages OO, mais dans les langages fonctionel on dit tous simplement qu’on va utiliser une fonction de haut niveau.
Ici on vois qu’on a définit une fonction récursive higherSum de la même form que les trois précédentes fonctions, la seule différence ici c’est que higherSum prend en plus une fonction f comme argument, cette fonction lui permettra d'implémenter la logique de somme on appliquant la fonction f sur chaque élément de l’interval a et b.
Bien sur étant donne que l’interface Function<Integer, Integer> est une interface SAM du package java.util.function (dont les type input et output sont pris ici pour Integer), on peut invoquer la fonction higherSum on lui passant une expression lambda comme paramètre.
Les expressions lambda sont colorées en vert.
On peut ainsi utiliser cette fonction pour calculer facilement:
La somme des carres des entiers entre a et b en lui passant la fonction anonyme: x -> x*x
La somme des cube des entiers entre a et b en lui passant la fonction anonyme: x -> x*x*x
ou la somme de … les possibilités sont illimités
On peut même utilise un concept du paradigme fonctionnel celui de currying et dont le principal objectif est de voir une fonction a n parametres retournant un résultat de type R, comme une HOF qui prend un seul paramètre et retourne un fonction qui prend (n-1) paramètres et retourne un résultat de type R.
Dans cet exemple la fonction curriendSum prend en parametre la fonction qu’on veut applliquer apres sur chaque element de l’interval, et retourn une fonction de type java.util.function.BiFunction qui prend deux parametre de type Integer et retourne un resultat de type Integer.
On peut ensuite utilise cette fonction pour le calcul des sommes sur un interval comme precedemment.
Considérons, l'exemple suivant:
On a un dépôt de produits, qui nous retourne une collections de produits, et on veut par exemple récupérer la référence de 10 produits répondant a un critère donnée.
Avant Java 8, on est oblige de parcourir la collection des produits, et pour chaque élément rencontre vérifier si il répond au critère voulu, si oui on l’ajoute a une liste produtsOfInterest, incrémenter une variable contenant numberOfProductSoFar qui si elle dépasse 10 on sort de la boucle.
Cette façon de faire est appelée “external iteration”, et c’est le développeur qui est en charge du parcourt de la collection et si demain il veut paralléliser ce traitement il doit tous repenser.
Avec Les Streams API l’iteration est interne et elle invisible par le developpeur, tous ce qu’il a a faire c’est de preciser les operations voulues (filter, map, limit, ….) c’est operations sont appelees “operations intermidiaires”, et chaque operation intermidiaire genere un autre Stream sans pour autant executant son traitement ( le stream final resultant regroupe l’ensemble des operations intermidiaires) de cette facon la source (qui peut etre soit une Collection, tableau, lignes d’un fichier ou autre) n’est parcouru qu’une seule fois si besoin est.
Un autre type d’operations sur les Streams est appele “operation terminal”. C’est qu’on on appele ces operations que la source est enfin parcourus (en interne) et pour chaque element on applique les operations intermidiaires.
Un autre avantage de l’iteration interne c’est qu’on peut paralleliser facilement ce traitement on appelant parallelStream au lieu de stream, ou appeler la method parallel() sur un stream ou rendre un stream sequentiel en applement la methode sequential() sur le stream.
1. A stream of infinite ints (tous les nombres entiers naturels)
2. Un stream nepeut etre consomer qu’une seul fois !!!