Functional Programming concepts… Java 8’s Stream has all of these except “zip”

Functional Programming concepts… Java 8’s Stream has all of these except “zip”

Bret Victor

I’ve been following Bret Victor over the past few years, watching, reading, and re-watching everything he puts out.

He’s obviously brilliant and has some great ideas and I’ve been trying to think of how I could build on them.

LightTable implemented about 10% of the programming part of “Inventing on Principle” (“coding without blinders”) while Swift/Xcode seem to implement about 20% of it. I admittedly jumped on the band-wagon early without a complete understanding of BV’s ideas when I created Zeta-code. While breaking code apart into methods is a good idea, it’s almost trivial compared to BV’s concept of “interacting with data”.

However, most of BV’s examples involve graphical data or mathematics.
While these are great things and he shows great interfaces, it misses what I (and a lot of us developers) deal with, which is text and objects
(or similar data structures). It also misses all of the “little details” like data-storage, formats, naming, and caching that are the hardest parts of “engineering” computer programs. (I say “little details” here with more than a hint of irony)

Things like lists, maps, sets, and text are what make up our daily-life.

This is in part why functional-programming and reactive-programming are becoming more popular today. They allow you to compose a few well-known functions to modify your data in a complex way. If all of your tools work together, it’s easier to do things than if you have a bunch of incompatible tools.

Perhaps by combining a graphical interface with FP principles we could create a new way of developing software. You could omit conditionals and loops entirely by using functional equivalents:

  •  If/then/else ~ Filter
  •  Reducing loops ~ Reduce
  •  Loops ~ ForEach
  •  Combining results ~ Concat or Zip

Of course, this doesn’t address the other parts of the programming: math, comparisons, pattern-matching, modifying text, etc., but there exist ways of doing these things (by providing examples, I’ll have to cover this later).

Let me know if you’re interested in this.

Java 8 Streams Examples

To better illustrate the benefit of Streams in Java 8, here are some examples of code from Java 7 compared to their new versions:

Finding a maximum

// Java 7
double max = 0;

for (Double d : list) {
  if (d > max) {
    max = d;
//Java 8
max =, Math::max);
// or
max =;

Calculating an average

double total = 0;
double ave = 0;
// Java 7
for (Double d : list) {
   total += d;
ave = total / ((double) list.size());
//Java 8
ave =;

Printing the numbers one through ten

// Java 7
for (int i = 1; i < 11; i++) {
// Java 8
IntStream.range(1, 11)
Stream.iterate(1, i -> i+1).limit(10)

Excerpt from “Whats New in Java 8

Tags: java8 streams

Java 8: Default Methods

In order to add the stream method (or any others) to the core Collections API, Java needed another new feature, Default methods (also known as Defender Methods or Virtual Extension methods). 

This way they could add new methods to the List interface for example without breaking all the existing implementations (backwards compatibility).

Default methods can be added to any interface. Like the name implies, any class that implements the interface but does not override the method will get the default implementation.

For example, the stream method in the Collection interface is defined something like the following:

default public Stream stream() {

You can always override a default method if you need different behavior.

Read More

Tags: Java8

Java 8: Lambda Expressions

The biggest new feature of Java 8 is language level support for lambda expressions (Project Lambda). 

A lambda expression is like syntactic sugar for an anonymous class with one method whose type is inferred (A lambda expression is not an anonymous class; it actually uses invokedynamic in the byte-code). However, it will have enormous implications for simplifying development.


The main syntax of a lambda expression is “parameters -> body”.
The compiler can usually use the context of the lambda expression to determine the functional interface being used and the types of the parameters. There are four important rules to the syntax:

  • Declaring the types of the parameters is optional.
  • Using parentheses around the parameter is optional if you have only one parameter. 
  • Using curly braces is optional (unless you need multiple statements).
  • The “return” keyword is optional if you have a single expression that returns a value.

Here are some examples of the syntax:

() -> System.out.println(this)
(String str) -> System.out.println(str)
str -> System.out.println(str)
(String s1, String s2) -> { return s2.length() - s1.length(); }
(s1, s2) -> s2.length() - s1.length()

The last expression could be used to sort a list; for example:

(String s1, String s2) -> s2.length() - s1.length());

In this case the lambda expression implements the Comparator interface to sort strings by length.

Read More

Tags: java8 lambdas

Hello Java 8

This article is part 1 of a series on Java 8.

Java 8 is a giant step forward for the Java language. In Project Lambda, Java gets a new closure syntax (lambda expressions), method-references, and default and static methods on interfaces. It manages to add many of the features of functional languages without losing the clarity and simplicity Java developers have come to expect. In addition, many of the existing Java core library classes have been enhanced with the new Streams API.

Aside from Project Lambda, Java 8 also gets a new Date and Time API (JSR 310), the Nashorn JavaScript engine, and removes the Permanent Generation from the HotSpot virtual machine, among other changes.

Why Lambda?

This is a two part question: firstly why the word “lambda”; secondly, why do we need lambda expressions in Java?

You might of heard of Lambda Calculus. If not please watch this Jim W. talk (at least the first ten minutes). Lambda Calculus was invented around the same time as the Turing Machine, and they are computationally equivalent. They also represent a duality that has existed in computer science since it’s foundation. A duality reflected in “imperative” languages versus “functional” languages. So this is where the word “lambda” comes from.

Why do we need lambdas? Over the past decade, functional languages, and languages with closures have gained in popularity. Although not the same thing, closures and functional programming are closely related. You can think of a closure as a block of code that can be passed around. Groovy, Scala, Clojure (of course) and to some degree JavaScript all have closures. A closure “closes” over variables from the surrounding scope; hence the name. Developers have hailed closures for making code more concise and reducing “boiler-plate” code. 

However, there is a second and perhaps more important reason for lambdas - the rise of multi-core processors. It is widely acknowledged that functional programming (in conjunction with immutable data structures) makes parallel programming easier to accomplish. However, without lambda expressions, functional programming is clunky and inefficient in Java (although certainly not impossible). With lambda expressions, method-references, and functional additions to the Java core libraries, Java 8 supports some functional programming. It even supports parallel operations with the new Stream API.

In the next post, I’ll cover the syntax of lambdas, method references, and default methods.

Tags: java8

Introduction to Scala: Part 4

This is the final part of a four part series.

For expressions

The for expression in Scala is a very powerful feature. It can used similar to a normal “for loop” but it can also be used to avoid null-pointer exceptions and for parallel programming. First we will discuss avoiding null-pointers.

To avoid null, Scala has Option. “Option” has two implementations: “Some” and “None”. Some wrapping a value, and None representing a null value.

For example, imagine you want to create a Person object only if “firstName” and “surname” are supplied.
Then using the scala command-line, define the Person class:

scala> case class Person(firstName: String, surname: String)
defined class Person

Define maybeFirstname and maybeSurname as instance of Option, with None for maybeSurname (meaning it was not supplied).

scala> val maybeFirstname = Option(“Adam”)
maybeFirstname: Option[java.lang.String] = Some(Adam)

scala> val maybeSurname = Option(null)
maybeSurname: Option[Null] = None

Then, when you use the following for-comprehension, you get a “None” instead of null or a “NullPointerException”.

scala> for (firstName <- maybeFirstname; surname <- maybeSurname)
yield Person(firstName, surname)
res1: Option[Person] = None

Now, redefine maybeSurname with a value and rerun the for-comprehension to get the Person.

scala> val maybeSurname = Option(“Davis”)
maybeSurname: Option[java.lang.String] = Some(Davis)

scala> for (firstName <- maybeFirstname; surname <- maybeSurname)
yield Person(firstName, surname)
res2: Option[Person] = Some(Person(Adam,Davis))

When multiple values are assigned using “<-” inside a for comprehension, each value will have “flatMap” called on it, and the “yield” expression results in having “map” called (which results in an “Option”). This works because Option is iterable (like a list with one or zero elements).

This means that for expressions are particularly useful for combinatorial algorithms. For example, this combines all combinations of (1,2) and (a,b):

scala> for (x <- List(1,2); y <- List(“a”,”b”)) yield (x,y)
res0: List[(Int, java.lang.String)] = List((1,a), (1,b), (2,a), (2,b))

Note that the resulting type depends on the type of the first element. So, if “x” was a “Set”, res0 would have been a “Set[(Int, String)]”.

For those who are interested, the equivalent to the above in Java 7 using javatuples would be something like the following:

// imports:
import static java.util.Arrays.asList;
import org.javatuples.Pair;
// code:
List<Pair<Integer,String> list = new ArrayList<>();
for (int x : asList(1, 2))
for (String y : asList(“a”, “b”))
list.add(Pair.with(x, y));

For expressions can also contains filters and definitions:

for {
p <- persons // a generator
n = // a definition
if (n startsWith “Foo”) // a filter
} yield n

Finally, if you desire to convert your for-expression to use parallel programming, you need only add one word (as of Scala 2.9), “par”.
Assuming “persons” is a collection (List or Set), the following would be executed in parallel:

for {
p <- persons.par
n =
if (n startsWith “Foo”)
} yield n

Previous Posts:

Scala: Part 1
Scala: Part 2
Scala: Part 3

Tags: Scala

Introduction to Scala: Part 3


Scala does not have interfaces, but has Traits instead, which is somewhat like a combined Interface and Abstract-base-class in Java. However, unlike anything in Java, Traits can be applied to classes or instances of classes and multiple Traits can be used.

Here’s an example:

class SpaceShuttle(val name:String) {
def launch = println(name + ” Take off!”)
trait MoonLander {
def land = println(“Landing!”)
class MoonShuttle(name:String) extends SpaceShuttle(name) with MoonLander {

A class can use any number of Traits using the “with” keyword.
So now we can do the following:

val apollo = new MoonShuttle(“Apollo 27”)

This would generate the following output:

Apollo 27 Take off!

To use multiple Traits you simply add them to the end, for example:

class MoonShuttle(name:String) extends SpaceShuttle(name) with MoonLander with Shuttle with Rocket

List and Apply

Scala’s core library includes an immutable List. A list can be created very easily.

scala> val list = List(1,2,3,4)
list: List[Int] = List(1, 2, 3, 4)

Read More

Tags: Scala tuples

Introduction to Scala: Part 2

Match is Switch on Steroids

You can use the match statement much like a switch statement. Check out the following code for an example of the syntax:

def wordFor(number:Int) = number match {
  case 1 => “one”
  case 2 => “two”
  case 3 => “three”
  case _ => “unknown”

There’s no need for a “return” or “break” keyword because the “match” statement actually returns whatever value is returned from the matched “case” statement.

Another thing “missing” in Scala (if your coming from Java) is the “instanceof” keyword and any casting. Instead, you can you just use a match statement like the following:

// return a Person or null if obj is a different type.
var person:Person = obj match {
case x:Person => x
case _ => null

One of the most powerful features of matching is using case classes.  Using case classes you are able to match values within a class.  Let’s take a look at a concrete example:

class Dimension(val width:Int, val height:Int)

case class Vertical(h:Int) extends Dimension(0, h)
case class Horizontal(w:Int) extends Dimension(w, 0)

def printDim(d : Dimension) = d match {
  case Vertical(value) => println(“Vert: ” + value)
  case Horizontal(value) => println(“Horiz: ” + value)

  case dim:Dimension => {
    print(“W: ” + dim.width + “, “)
    println(“H: ” + dim.height)

  case null => println(“Invalid input”)
printDim(Vertical(10)) // Vert: 10
printDim(Horizontal(30)) // Horiz: 30

The above “printDim” function uses the match statement to pull out the appropriate value if the given Dimension is an instance of Vertical or Horizontal. Of course, this only works if you define the case classes, which makes them similar to Java enums, but more flexible.

Catching Exceptions in Scala is similar to using the “match” statement. For example, see the following code where the last block is executed for all other types of exceptions:

try {…}
 catch {
  case e:SQLException => println(“Database error”)
  case e:MalformedURLException => println(“Bad URL”)
  case e => {
    println(“Some other exception type:”)

Previous Post: Scala: Part 1

NextScala: Part 3

Tags: Scala

Introduction to Scala: Part 1

What is Scala?

Scala is an open-source language that runs on the JVM. It was developed at the Programming Methods Laboratory of the Swiss Federal Institute of Technology (EPFL), mainly by Martin Odersky (a co-designer of Java generics).

TypeSafe, a private company, offers training, commercial maintenance, support, and operations tools for Scala, as well as Akka and Play.

The Scala website has the following description of the language:

Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive. Code sizes are typically reduced by a factor of two to three when compared to an equivalent Java application. -

Hello World

Here’s a simple HelloWorld example in Scala:

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

You’ll notice that HelloWorld is declared as an object. This is similar to the keyword static in Java, except that instead of putting the keyword on every method and field, you just wrap everything up in one block. Since the main method in Java is static, we need to put the main method in an object in Scala.

The def keyword is used to define functions.

The next thing you might notice is that types are declared after the parameter name. In Scala type declarations always come on the right-side after a colon.

Array[String] is the equivalent of String[] in Java. Everything in Scala is an Object, including arrays.

Lastly, you’ll see that the println function is called which is equivalent to System.out.println in Java.

Read More

Tags: Scala