Functional Programming - StefanSchade/Java-Language-Examples GitHub Wiki

Table of Contents

  • Principle of Functional Programing is, not use traditional loops

  • → Benefits in parallel computing

  • whole program of a functional language is a composition of functions

  • composition instead of communication f(g(a), h(b), g(c))

  • stateless functions g and h can be evaluated in any order

    • even in parallel

    • communication ONLY through return values

    • no race conditions, synchronisation etc.

    • much simpler than mutithreading

    • input → output (always the same), function is stateless, aka purety,

    • absence of side effects, referential transparency, Pure functions

      • ⇒ no state ⇒ no variables

      • ⇒ no memory, no assignments, no loops

  • How can we program without loops → Example

  • developed in 1935 by Alonzo Church, one of the fathers of computers

  • first 'programming language'

  • very abstract mathematical language

  • main objects are functions in the mathematical sense

2nd proper programming language after Fortran modern derivative languages: Scheme and Closjure (2007, runns on JVM)

modern family member F# (Microsoft .NET, multi-paradigm i.e. not just functional, also imperative features)

Lambda expressions are a compact syntax to implementing Functional Interfaces. Thus they are an alternative to anonymous classes.

The run() method can be implemented without even mentioning it, as Functional Interfaces have only one abstract method
  Runnable r = () -> {
            System.out.println("A compact runnable");
        };
    Thread t = new Thread(r);
The interface Runnable does not need to be specified, it is inferrable from the context i.e. the constructor signature: Thread(Runnable r). The braces can be omitted since there is only one statement in the body of the lambda.
 Thread t = new Thread(() -> System.out.println("An implicit Runnable without braces!"));
The syntax of a lambda expression:
 FunctionalInterface myImplementation = (Arg) -> {codeblock; return returnvalue};
  • FunctionalInterface: The context helps the compiler to infer the type of the interface.

  • myImplementation: The lambda can be assigned to an instance, it might also be part of a return-statement or an argument of a method or a consturctor.

  • instance: The Argument List .

    helps the compiler to infer the type of the interface.
⚠️ **GitHub.com Fallback** ⚠️