Welcome!

Java IoT Authors: Elizabeth White, Pat Romanski, Liz McMillan, William Schmarzo, Stackify Blog

Related Topics: Java IoT

Java IoT: Article

The Rise of Functional Java Programming

Better living without side effects

Using the principle of referential transparency, and substituting the appropriate body of the “sum” function at each step, we can proceed to rewrite this as follows:

sum 1:[2, 3, 4, 5]
1 + sum [2, 3, 4, 5]
1 + sum 2:[3, 4, 5]
1 + 2 + sum [3, 4, 5]
1 + 2 + sum 3:[4, 5]
1 + 2 + 3 + sum [4, 5]
1 + 2 + 3 + sum 4:[5]
1 + 2 + 3 + 4 + sum [5]
1 + 2 + 3 + 4 + sum 5:[]
1 + 2 + 3 + 4 + 5 + sum []
1 + 2 + 3 + 4 + 5 + 0

Having made each step of the computation explicit, the derivation of the final result is clear. What’s more, we can be certain that each step in the above derivation completely describes the computation, as we’ve given up the possibility of implicit “side effects” happening between steps. You can imagine that if the “sum” function had a side-effect (like updating the input list) this simple two-line example would become much more difficult to understand.

Because a functional program implies that you can always substitute a function call with its result, there are two very important things that our compiler can do to help us without any effort on our part. The first is that, according to the principle of referential transparency, the compiler can substitute the final result for the call to “sum” at compile-time, without changing the behavior of the program. This has the effect, in our example, of doing no runtime computation at all!

In more realistic cases, the compiler may not be able to compute the entire function ahead of time, but with this principle as a guide it can still simplify the inevitable runtime computation by partially evaluating as much of it as possible at compile-time. The second thing the compiler can do is to perform the final computation in parallel where possible. Given some simple properties of the functions involved (in this case, the fact that a + b + c = a + (b + c) = (a + b) + c), the compiler could easily generate code to compute the final sum as (with concurrent evaluation denoted by parentheses):

1 + 2 + 3 + 4 + 5 + 0
(1 + 2) + (3 + 4) + (5 + 0)
3 + 7 + 5
(3 + 7) + (5)
10 + 5
(10 + 5)
15

Remarkably, the compiler can (given just these few reasonable assumptions) produce a very specialized, efficient executable from our compact functional program. The key to passing all of this complexity off to the compiler is that we go out of our way to leave the compiler as many implementation options as possible. To summarize this viewpoint: functional programs describe what is to be computed, allowing functional compilers to decide how to compute it. Unnecessary complexity creeps into software projects where these problems of what and how are intermixed.

Introduction to Scala
A good way for Java programmers to experiment with functional programming concepts is to give Scala a try. Scala is an interesting programming language first released in 2003 by Martin Odersky, a computer science professor at the Swiss Federal Institute of Technology, and one of the designers of Java generics. Scala is a multi-paradigm language, smoothly integrating features of both object-oriented and functional languages. Most importantly it is fully interoperable with Java. It compiles to JVM bytecodes (i.e., standard .class files), Java libraries can be used freely in Scala programs, and it is possible to inherit from Java classes and implement Java interfaces directly in Scala. An Eclipse plug-in is even available.

Installation Instructions via the Eclipse Plug-in
If you’re an Eclipse user, it’s easy to get started with Scala by installing the Scala Eclipse Plug-in. You don’t even have to install Scala first. Just select:

Help -> Software Updates -> Find and Install -> Search for new features to install

and create a new remote site called “Scala Plugin Update Site” with this URL:

http://scala-lang.org/downloads/scala-plugin

Install the feature Scala Plugin UpdateSite. If you get an error that package org.eclipse.pde.runtime is missing, then go back to:

Help -> Software Updates -> Find and Install -> Search for new features to install

and select The Eclipse Project Updates, expand the category corresponding to your version of Eclipse, and select the Eclipse Plugin Development Environment. Install it and restart Eclipse. That plug-in includes the required org.eclipse.pde.runtime package, so once it’s installed you should be able to install the Scala plug-in.

If you are not an Eclipse user, you can install Scala the traditional way, starting from this URL:

http://www.scala-lang.org/downloads/index.html

Once you’ve installed Scala, create a new Scala Project. Create a package called com.lab49.example and within it create a Scala Object called Main with the following contents:

package com.lab49.example;

object Main {
    def main(args: Array[String]) {
      println(“Hello, world!”)
    }
}

Select Run as Scala Application. If it displays Hello, world then congratulations! You have just written your first Scala application.

Now let’s try rewriting the sum function in Scala:

package com.lab49.example;

object Main {
    def sum (l: List[Int]): Int = {
      l match {
        case Nil => 0
        case ::(x,xs) => x + sum(xs)
      }
    }

    def main(args: Array[String]) {
      println (sum(List(1, 2, 3, 4, 5)));
    }

}

This is slightly more verbose, but similar in spirit to the two-line Haskell example we started with. The Haskell version didn’t declare a package, enclosing class, or Main function, so a fair comparison is to look at only the sum function that is six lines long in Scala and includes type declarations. Note the pattern-matching syntax, for example, the use of :: to match a list and split the head node from the remaining nodes. This is an example of a nice Scala feature called case classes that lets you write pattern-matching case statements for your own classes as well as built-in ones.

Note that it’s not the objective of this paper to be a Scala tutorial. There are already many of those on the Web. But we want to introduce Scala because it provides excellent support for functional programming, fits well with the Java technology stack, and is gaining momentum in the Java community.

More Stories By Joe Morrison

Joe Morrison is a managing consultant at Lab49, and has over 20 years of experience leading engineering teams in designing and building complex network-based applications. His projects have ranged from distributed object research at Verizon Laboratories, to value chain management software at Benchmarking Partners in Boston, to in-the-trenches SOA projects for financial services firms in New York. Joe holds a BMath degree in computer science from the University of Waterloo, and a master's degree in computer science from MIT. He is a regular blogger on http://blog.lab49.com/.

More Stories By Kalani Thielen

Kalani Thielen is a Lab49 technology consultant, working in the financial services industry. Prior to joining Lab49 in 2006, he worked for six years developing products for the publishing, advertising, and communications industries. As a specialist in programming language theory, his present work focuses on the development and certification of compilers for bond pricing and trading languages.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
Mobile device usage has increased exponentially during the past several years, as consumers rely on handhelds for everything from news and weather to banking and purchases. What can we expect in the next few years? The way in which we interact with our devices will fundamentally change, as businesses leverage Artificial Intelligence. We already see this taking shape as businesses leverage AI for cost savings and customer responsiveness. This trend will continue, as AI is used for more sophistica...
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Keisoku Research Consultant Co. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...
There is huge complexity in implementing a successful digital business that requires efficient on-premise and cloud back-end infrastructure, IT and Internet of Things (IoT) data, analytics, Machine Learning, Artificial Intelligence (AI) and Digital Applications. In the data center alone, there are physical and virtual infrastructures, multiple operating systems, multiple applications and new and emerging business and technological paradigms such as cloud computing and XaaS. And then there are pe...
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
SYS-CON Events announced today that Suzuki Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...