Some key features of Scala include:
1. It allows blending of functional programming and object-oriented programming for more concise and powerful code.
2. The static type system allows for type safety while maintaining expressiveness through type inference, implicits, and other features.
3. Scala code interoperates seamlessly with existing Java code and libraries due to its compatibility with the JVM.
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.
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.
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Philip Schwarz
(download for better quality)
Introducing Assignment invalidates the Substitution Model of Evaluation and violates Referential Transparency
- as explained in SICP (the Wizard Book)
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developer’s toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
Slideshare hasn't imported my notes, so here's the link to the Google Presentation: https://goo.gl/Gl4Vhm
Haskell is a statically typed, non strict, pure functional programming language. It is often talked and blogged about, but rarely used commercially. This talk starts with a brief overview of the language, then explains how Haskell is evaluated and how it deals with non-determinism and side effects using only pure functions. The suitability of Haskell for real world data science is then discussed, along with some examples of its users, a small Haskell-powered visualization, and an overview of useful packages for data science. Finally, Accelerate is introduced, an embedded DSL for array computations on the GPU, and an ongoing attempt to use it as the basis for a deep learning package.
We will be showing the use case of the implementation of a Data Pipeline in the maritime domain @Windward via Spark applications.
The process was converting a Monolith application to a fully distributed and scalable application.
We'll be talking about all the tools and the process of taking an idea and developing Spark applications around it, And will show the development of an application End to End, from DevOps to the method of thinking about the development of applications, showing use-cases and the "lessons learned" at Windward Ltd, I hope that after the talk, it will give you some more Practical tools to "Spark"ing your way around.
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Philip Schwarz
(download for better quality)
Introducing Assignment invalidates the Substitution Model of Evaluation and violates Referential Transparency
- as explained in SICP (the Wizard Book)
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developer’s toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
Slideshare hasn't imported my notes, so here's the link to the Google Presentation: https://goo.gl/Gl4Vhm
Haskell is a statically typed, non strict, pure functional programming language. It is often talked and blogged about, but rarely used commercially. This talk starts with a brief overview of the language, then explains how Haskell is evaluated and how it deals with non-determinism and side effects using only pure functions. The suitability of Haskell for real world data science is then discussed, along with some examples of its users, a small Haskell-powered visualization, and an overview of useful packages for data science. Finally, Accelerate is introduced, an embedded DSL for array computations on the GPU, and an ongoing attempt to use it as the basis for a deep learning package.
We will be showing the use case of the implementation of a Data Pipeline in the maritime domain @Windward via Spark applications.
The process was converting a Monolith application to a fully distributed and scalable application.
We'll be talking about all the tools and the process of taking an idea and developing Spark applications around it, And will show the development of an application End to End, from DevOps to the method of thinking about the development of applications, showing use-cases and the "lessons learned" at Windward Ltd, I hope that after the talk, it will give you some more Practical tools to "Spark"ing your way around.
Presentation on handling non-existence of data in Java et. al. (e.g. the problem with pesky nulls) and an introduction to the Option monad in Scala as a "solution" to this problem.
I presented this talk June, 28th 2013 at CPH Scala Group meeting, and a week later, July 3rd, at the "Scala User Group Århus" meetup.
In this short introduction, I try to frame the problem, i.e. the large amounts of error-prone null-checking code we usually have to write in Java, and Introduce the Option monad (Some/None) in Scala, as a solution. I explain the basics of what the Option class provides, and various ways of using it, ranging from basic level isEmtpy, over pattern-matching to more advanced fully functional "collection-style" (e.g. map, flatMap) operations and finally by using the for-comprehension.
Also includes links to relevant resources for further reading on the last slide.
The objectives of the seminar are to shed a light on the premises of FP and give you a basic understanding of the pillars of FP so that you would feel enlightened at the end of the session. When you walk away from the seminar you should feel an inner light about the new way of programming and an urge & motivation to code like you never before did!
Functional programming should not be confused with imperative (or procedural) programming. Neither it is like object oriented programming. It is something different. Not radically so, since the concepts that we will be exploring are familiar programming concepts, just expressed in a different way. The philosophy behind how these concepts are applied to solving problems are also a little different. We shall learn and talk about essentially the fundamental elements of Functional Programming.
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...Andrew Phillips
Slides from the presentation "Analysing Scala Puzzlers: Essential and Accidental Complexity in Scala" at the Boston Area Scala Enthusiasts meetup, by Andrew Phillips & Nermin Serifovic. See http://www.meetup.com/boston-scala/events/228136405/
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Andrew Phillips
Slides from the presentation "Analysing Scala Puzzlers: Essential and Accidental Complexity in Scala" at Scala Up North 2015, by Andrew Phillips & Nermin Serifovic. See http://scalaupnorth.com/speakers.html#andrew
ScalaDays 2013 Keynote Speech by Martin OderskyTypesafe
Scala gives you awesome expressive power, but how to make best use of it? In my talk I will discuss the question what makes good Scala style. We will start with syntax and continue with how to name things, how to mix objects and functions, where (and where not) to use mutable state, and when to use which design pattern. As most questions of style, the discussion will be quite subjective, and some of it might be controversial. I am looking forward to discuss these topics with the conference attendees.
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.
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
Using InfluxDB for real-time monitoring in JmeterKnoldus Inc.
Explore the integration of InfluxDB with JMeter for real-time performance monitoring. This session will cover setting up InfluxDB to capture JMeter metrics, configuring JMeter to send data to InfluxDB, and visualizing the results using Grafana. Learn how to leverage this powerful combination to gain real-time insights into your application's performance, enabling proactive issue detection and faster resolution.
Intoduction to KubeVela Presentation (DevOps)Knoldus Inc.
KubeVela is an open-source platform for modern application delivery and operation on Kubernetes. It is designed to simplify the deployment and management of applications in a Kubernetes environment. KubeVela is a modern software delivery platform that makes deploying and operating applications across today's hybrid, multi-cloud environments easier, faster and more reliable. KubeVela is infrastructure agnostic, programmable, yet most importantly, application-centric. It allows you to build powerful software, and deliver them anywhere!
Stakeholder Management (Project Management) PresentationKnoldus Inc.
A stakeholder is someone who has an interest in or who is affected by your project and its outcome. This may include both internal and external entities such as the members of the project team, project sponsors, executives, customers, suppliers, partners and the government. Stakeholder management is the process of managing the expectations and the requirements of these stakeholders.
Introduction To Kaniko (DevOps) PresentationKnoldus Inc.
Kaniko is an open-source tool developed by Google that enables building container images from a Dockerfile inside a Kubernetes cluster without requiring a Docker daemon. Kaniko executes each command in the Dockerfile in the user space using an executor image, which runs inside a container, such as a Kubernetes pod. This allows building container images in environments where the user doesn’t have root access, like a Kubernetes cluster.
Efficient Test Environments with Infrastructure as Code (IaC)Knoldus Inc.
In the rapidly evolving landscape of software development, the need for efficient and scalable test environments has become more critical than ever. This session, "Streamlining Development: Unlocking Efficiency through Infrastructure as Code (IaC) in Test Environments," is designed to provide an in-depth exploration of how leveraging IaC can revolutionize your testing processes and enhance overall development productivity.
Exploring Terramate DevOps (Presentation)Knoldus Inc.
Terramate is a code generator and orchestrator for Terraform that enhances Terraform's capabilities by adding features such as code generation, stacks, orchestration, change detection, globals, and more . It's primarily designed to help manage Terraform code at scale more efficiently . Terramate is particularly useful for managing multiple Terraform stacks, providing support for change detection and code generation 2. It allows you to create relationships between stacks to improve your understanding and control over your infrastructure . One of the key features of Terramate is its ability to detect changes at both the stack and module level. This capability allows you to identify which stacks and resources have been altered and selectively determine where you should execute commands.
Clean Code in Test Automation Differentiating Between the Good and the BadKnoldus Inc.
This session focuses on the principles of writing clean, maintainable, and efficient code in the context of test automation. The session will highlight the characteristics that distinguish good test automation code from bad, ultimately leading to more reliable and scalable testing frameworks.
Integrating AI Capabilities in Test AutomationKnoldus Inc.
Explore the integration of artificial intelligence in test automation. Understand how AI can enhance test planning, execution, and analysis, leading to more efficient and reliable testing processes. Explore the cutting-edge integration of Artificial Intelligence (AI) capabilities in Test Automation, a transformative approach shaping the future of software testing. This session will delve into practical applications, benefits, and considerations associated with infusing AI into test automation workflows.
State Management with NGXS in Angular.pptxKnoldus Inc.
NGXS is a state management pattern and library for Angular. NGXS acts as a single source of truth for your application's state - providing simple rules for predictable state mutations. In this session we will go through the main for components of NGXS -Store, Actions, State, and Select.
Authentication in Svelte using cookies.pptxKnoldus Inc.
Svelte streamlines authentication with cookies, offering a secure and seamless user experience. Effortlessly manage sessions by storing tokens in cookies, ensuring persistent logins. With Svelte's simplicity, implement robust authentication mechanisms, enhancing user security and interaction.
OAuth2 Implementation Presentation (Java)Knoldus Inc.
The OAuth 2.0 authorization framework is a protocol that allows a user to grant a third-party web site or application access to the user's protected resources, without necessarily revealing their long-term credentials or even their identity. It is commonly used in scenarios such as user authentication in web and mobile applications and enables a more secure and user-friendly authorization process.
Supply chain security with Kubeclarity.pptxKnoldus Inc.
Kube clarity is a comprehensive solution designed to enhance supply chain security within Kubernetes environments. Kube clarity enables organizations to identify and mitigate potential security threats throughout the software development and deployment process.
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
In this session, we will delve into the world of web scraping with JSoup, an open-source Java library. Here we are going to learn how to parse HTML effectively, extract meaningful data, and navigate the Document Object Model (DOM) for powerful web scraping capabilities.
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
Dive into the fundamental aspects of Akka gRPC and learn to leverage its power in building compact and efficient distributed systems. This session aims to equip attendees with the essential skills and knowledge to leverage Akka and gRPC effectively in building robust, scalable, and distributed applications.
Entity Core with Core Microservices.pptxKnoldus Inc.
How Developers can use Entity framework(ORM) which provides a structured and consistent way for microservices to interact with their respective database, prompting independence, scaliblity and maintainiblity in a distributed system, and also provide a high-level abstraction for data access.
Introduction to Redis and its features.pptxKnoldus Inc.
Join us for an interactive session where we'll cover the fundamentals of Redis, practical use cases, and best practices for incorporating Redis into your projects. Whether you're a developer, architect, or system administrator, this session will equip you with the knowledge to harness the full potential of Redis for your applications. Get ready to elevate your understanding of in-memory data storage and revolutionize the way you handle data in your projects with Redis
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
In this Webinar, will talk on GraphQL with .NET, that provides a modern and flexible approach to building APIs. It empowers developers to create efficient and tailored APIs that meet the specific needs of their applications and clients.
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
These packages and topics cover various aspects of .NET development, offering solutions for common needs in software development, including logging, database interaction, API communication, testing, security, and more. Depending on the requirements of your project, incorporating these packages can significantly enhance the development process.
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
Data Quality in Test Automation: Navigating the Path to Reliable Testing" delves into the crucial role of data quality within the realm of test automation. It explores strategies and methodologies for ensuring reliable testing outcomes by addressing challenges related to the accuracy, completeness, and consistency of test data. The discussion encompasses techniques for managing, validating, and optimizing data sets to enhance the effectiveness and efficiency of automated testing processes, ultimately fostering confidence in the reliability of software systems.
K8sGPTThe AI way to diagnose KubernetesKnoldus Inc.
K8sGPT is a tool for scanning your Kubernetes clusters, diagnosing and triaging issues in simple english. It has SRE experience codified into its analyzers and helps to pull out the most relevant information to enrich it with AI. In the session we will integrate OpenAI with K8sGPT to diagnose our Kubernetes Cluster.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
2. Programming Languages
One approach to the software crisis is to introduce new
programming languages that supports following :
→Reusability
→ Clear , Concise and High performance code.
→ Rapid prototyping
→ Reduces time and cost for development
4. Scala programming language
Born from the mind of Martin Odersky.
A good mix of :
→ Object orientation
→ functional programming
→ A powerful type system code
→ Eligent and powerful code then other
languages
6. Scala attempts to blend three dichotomies of
thought into one language. These are:
→ Functional programming and object-oriented
programming
→ Expressive syntax and static typing
→ Advanced language features and rich Java
integration
Let us understand these one-by-one :-
7. Functional programming and object
oriented programming
→ Functional programming is style of programming in which the basic
method of computation is the application of functions to arguments.
→ Functional programming puts special emphasis on the “verbs” of a
program & Object-oriented programming puts special emphasis on
“nouns” and attaches verbs to them.
→ The two approaches are almost inverses of each other, with one
being “top down” and the other “bottom up.”
→ Functional programming approaches software as the combination
and application of functions.
→ It tends to decompose software into behaviors, or actions that need
to be performed, usually in a bottom-up fashion.
8. Didn't understood...Have a look ?
Scenerio : “A Lion catches a deer and eats it.”
The OOPS approach :
class Deer
class Lion {
def catch(d: Deer): Unit = ...
def eat(): Unit = ...
}
val lion = new Lion
val deer = new Deer
lion.catch(deer)
lion.eat()
9. Functional programming approach
trait Lion
trait Deer
trait Catch
trait FullTummy
def catch(hunter: Lion, prey: deer): Lion with Catch
def eat(consumer: Lion with Catch): Lion with FullTummy
val story = (catch _) andThen (eat _)
story(new Lion, new Deer)
10. Static typing and expressiveness
The Scala type system allows expressive code.
Scala made a few simple design decisions that help
make it expressive:
- Changing sides of type annotation
- Type inference
- Scalable syntax
- User-defined implicits
11. Transparently working with the JVM
→ Seamless integration with Java and the JVM
→ Using Java libraries from Scala is seamless
because Java idioms map directly into Scala
idioms.
→ libraries written in Java can be imported into
Scala as is.
12. Recursion
Recursion plays a larger role in pure functional
programming than in imperative programming, in part
because of the restriction that variables are immutable.
For example, you can’t have loop counters, which would
change on each pass through a loop. One way to
implement looping in a purely functional way is with
recursion.
Lets have a look :
Calculating factorials provides a good example. Here is an
imperative loop implementation.
13. Imperative loop implementation
def factorialWithLoop(i: BigInt): BigInt = {
var resultantValue = BigInt(1)
for (h <- 2 to i.intValue)
resultantValue *= h
resultantValue
}
for (i <- 1 to 10)
println("factorial of " + i + " is " + factorialWithLoop(i))
14. Functional Approach
def factorial_Functional(i: BigInt): BigInt = i match {
case _ if i == 1 => i
case _ => i * factorial_Functional(i - 1)
}
for (i <- 1 to 10)
println("factorial of " + i + " is " + factorial_Functional(i))
How short and effective it is ..... !
15. Introduction to implicits
Scala provides an implicit keyword that can be used in two ways:
→ method or variable definitions
→ method parameter lists
scala> def findAnInt(implicit x : Int) = x
findAnInt: (implicit x: Int)Int
scala> findAnInt
<console>:7: error: could not find implicit value for parameter x: Int
findAnInt
^
16. The findAnInt method is called without specifying any
argument list. The compiler complains that it can’t find an
implicit value for the x parameter. We’ll provide one, as
follows:
scala> implicit val test = 5
test: Int = 5
scala> findAnInt
res3: Int = 5
17. Avoid call site evaluation ?
Sometimes we want arguments not be evaluated
at call site :
def executeMe(msgString: () => String) {
println(msgString())
}
Now calling the method like :
executeMe(() => "This" + " is" + " not"+ " looking" + "
good!")
Not looking good...isn’t it?
18. How we can do this in a good way :
We can use => in a type annotation to define a by-name
parameter.
// by-name parameter
def iAmOk(msgString: => String) { println(msgString) }
Now calling it as :
/*
* Using by-name Parameter
*/
iAmOk("This" + " is" + " an" + " use"+" case"+ " by-name" + " param.")
19. Partial Functions :
→ Need not be defined on its whole domain
→ PartialFunction is a subtype of Function1:
trait PartialFunction [-A, +B] extends A => B
→ Use isDefinedAt to determine whether a partial
function is defined for a given value
or not.
20. Using isDefinedAt :
object KnolXPartialFunction {
// defined a map
val KnolXMap = Map(1 -> "Neelkanth", 2 -> "Sachdeva")
def main(args: Array[String]) {
val booleanAnswer1 = KnolXMap.isDefinedAt(1)
println("The Answer is " + booleanAnswer1)
val booleanAnswer2 = KnolXMap.isDefinedAt(3)
println("The Answer is " + booleanAnswer2)
}
}
Output should be as :
The Answer is true
The Answer is false
21. Use a block of case alternatives to define a
partial function literal :
scala> (’a’ to ’f’).zipWithIndex filter {
| case (_, i) => i % 2 == 0
|}
Result should be like this :
res0: ... = Vector((a,0), (c,2), (e,4))
22. Using the right collection
The Scala collections library is the single most impressive
library in the Scala ecosystem. The Scala collections provide
many ways of storing and manipulating data, which can be
overwhelming. Because most of the methods defined on Scala
collections are available on every collection.
Scala’s collections also split into three dichotomies:
→ Immutableand mutable collections
→ Eager and delayed evaluation
→ Sequential and parallel evaluation
23. The collection hierarchy
Traversable : The Traversable trait is defined in terms of the
foreach method.This method is an internal iterator---that is, the
foreach method takes a function that operates on a single
element of the collection and applies it to every element of the
collection. Travers-able collections don’t provide any way to
stop traversing inside the foreach.
Iterable : The Iterable trait is defined in terms of the iterator
method. This returns an external iterator that you can use to
walk through the items in the collection.
scala> val names = Iterable("Josh", "Jim")
names: Iterable[java.lang.String] = List(Josh, Jim)
24. Seq : The Seq trait is defined in terms of the length
and apply method. It represents collections that
have a sequential ordering. We can use the
apply method to index into the collection by its
ordering. The length methodreturns the size of
the collection.
scala> val x = Seq(2,1,30,-2,20,1,2,0)
x: Seq[Int] = List(2, 1, 30, -2, 20, 1, 2, 0)
scala> x.tails map (_.take(2)) filter (_.length > 1)
map (_.sum) toList
res0: List[Int] = List(3, 31, 28, 18, 21, 3, 2)
25. LinearSeq: The LinearSeq trait is used to denote that a
collection can be split into a head and tail component.
IndexedSeq: The IndexedSeq trait is similar to the Seq trait
except that it implies that random access of collection
elements is efficient that is, accessing elements of a
collectionshould be constant or near constant.
scala> val x = IndexedSeq(1, 2, 3)
x: IndexedSeq[Int] = Vector(1, 2, 3)
scala> x.updated(1, 5)
res0: IndexedSeq[Int] = Vector(1, 5, 3)
Set
Map
26. Some special & powerful collection methods:
→ sliding : Groups elements in fixed size blocks by passing a
”sliding window” over them .
→ Curried methods : A method can have more than one
parameter list, which is called currying2 .
→ foldLeft : foldLeft transforms a collection into a single value.
27. Using sliding method :
object KnolXSliding {
def KnolXSlide = {
1 to 6 sliding 4 foreach println
}
def main(args: Array[String]) {
// Call the sliding method
KnolXSlide
}
}
Output should be :
Vector(1, 2, 3, 4)
Vector(2, 3, 4, 5)
Vector(3, 4, 5, 6)
28. Using Curried methods :
object KnolXCurried {
// Passing more then one parameters
def KnolXadd(a: Int)(b: Int)(c: String) =
println("The Tota Sum is "+ (a + b) + " " + c)
def main(args: Array[String]) {
KnolXadd(2)(9)("Wowwwwwww !")
}
}
Output should be :
The Total Sum is 11 Wowwwwwww !
29. Using foldLeft method :
object KnolXfoldLeft {
def main(args: Array[String]) {
val addAll = Seq(1, 2, 3).foldLeft(0)(_ + _)
println("Sum is"+addAll)
}
}
Output should be :
Sum is 6