CSC/ECE 517 Fall 2014/ch1a 9 kn

From Expertiza_Wiki
Revision as of 17:57, 17 September 2014 by Vgarg2 (talk | contribs)
Jump to navigation Jump to search

Functional Programming Languages i.e Scala over Object Oriented Languages i.e Java

What is Functional Programming

Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions. In functional programming, programs are executed by evaluating expressions, in contrast with imperative programming where programs are composed of statements which change global state when executed. Functional programming typically avoids using mutable state. Examples of functional Programming languages are:

  • Haskell
  • Scala
  • Erlang

What is Object-oriented Programming

Object-oriented programming (OOP) is a programming language model which is organized around objects rather than "actions" and data rather than logic. A program has always been thought as a logical function that takes input data, processes it and produces the output. Object oriented programming cares about the objects we want to manipulate rather than the logic required to manipulate them. Objects here are usually instances of classes which are used to design applications and computer programs. Object-oriented programming languages have a come a long way starting from Simula all the way to languages like JAVA, Ruby etc. Some of the key features of object oriented programming languages are:

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Reflection
  • Abstraction

Introduction to Scala

Scala is an acronym for “Scalable Language”. It is an object- functional programming and scripting language which fuses functional and object-oriented programming in a practical package. Scala is now being used in a rapidly increasing number of open source projects and companies. It provides the core infrastructure for sites such as Twitter, LinkedIn, Foursquare, Tumblr, and Klout.

Aspects of Scala

The major aspects of Scala are:

  • Object oriented

Scala is a pure-bred object-oriented language. Conceptually, every value is an object and every operation is a method-call. The language supports advanced component architectures through classes and traits. Many traditional design patterns in other languages are already natively supported in SCALA.

  • Functional

Even though its syntax is fairly conventional, Scala is also a full-blown functional language. Many of Scala's design decisions were inspired by criticism over the shortcomings of Java. Scala has full support for functional programming concepts such as currying, pattern matching, algebraic data types, lazy evaluation, tail recursion, immutability, etc.

  • Seamless Interoperability with Java

Scala source code is intended to be compiled to Java bytecode, so that the resulting executable code runs on a Java virtual machine. Java libraries may be used directly in Scala code, and vice versa.

A simple "Hello World" example in Scala:


 object HelloWorld extends App {
   println("Hello, World!")
 }

Introduction to Java

Java is one of the more advanced and popular object-oriented based computer programming language. Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. Java applications are typically compiled to byte-code(class file) that can run on any Java virtual machine (JVM) regardless of computer architecture. The presence of Java Byte Code makes the language portable. There were five primary goals in the creation of the Java language:

  • It should be "simple, object-oriented and familiar"
  • It should be "robust and secure"
  • It should be "architecture-neutral and portable"
  • It should execute with "high performance"
  • It should be "interpreted, threaded, and dynamic"

Syntactically Java is similar to C++ and a “Hello World” program in Java would look as follows:

class HelloWorldApp {
    public static void main(String[] args) {
         System.out.println("Hello World!"); 
    }
}

Features of Scala

  • Support for Higher-Order Functions

Scala allows the definition of higher-order functions. These are functions that take other functions as parameters, or whose result is a function. Here is a function apply which takes another function f and a value v and applies function f to v:

def apply(f: Int => String, v: Int) = f(v)

Higher-order functions are very useful for refactoring code and reduce the amount of repetition. For example, typically most for loops can be expressed using maps. Custom iteration schemes, such as parallel loops, can be easily expressed using HOFs.

  • Immutable Collections

Scala collections systematically distinguish between mutable and immutable collections. Immutable collections, by contrast, never change. You have still operations that simulate additions, removals, or updates, but those operations will in each case return a new collection and leave the old collection unchanged. Similarly, all of the collection objects (container types) in Scala, e.g. linked lists, arrays, sets and hash tables, are available in mutable and immutable variants, with the immutable variant considered the more basic and default implementation.This allows for very easy concurrency — no locks are needed as no shared objects are ever modified.

  • Currying

Methods may define multiple parameter lists. When a method is called with a fewer number of parameter lists, then this will yield a function taking the missing parameter lists as its arguments.

  • Pattern Matching

Scala has built-in support for pattern matching, which can be thought of as a more sophisticated, extensible version of a switch statement, where arbitrary data types can be matched (rather than just simple types like integers, booleans and strings), including arbitrary nesting. A special type of class known as a case class is provided, which includes automatic support for pattern matching and can be used to model the algebraic data types used in many functional programming languages. Scala has a built-in general pattern matching mechanism. It allows to match on any sort of data with a first-match policy. Here is a small example which shows how to match against an integer value:

object MatchTest1 extends App {
  def matchTest(x: Int): String = x match {
    case 1 => "one"
    case 2 => "two"
    case _ => "many"
  }
  println(matchTest(3))
}

The block with the case statements defines a function which maps integers to strings. The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object.

  • Lazy evaluation

Since pure computations are referentially transparent they can be performed at any time and still yield the same result. This makes it possible to defer the computation of values until they are needed, that is, to compute them lazily. Lazy evaluation avoids unnecessary computations and allows, for example, infinite data structures to be defined and used.

  • Tail Recursion

A function can be called tail recursive when the last thing that happened was a call to itself, and no other recursive calls were made earlier. A clever compiler can then avoid adding a new frame to the stack, thus saving memory. Unlike Java, Scala has this capability. For example, simple reverse function can easily be converted into using tail recursion by adding a variable to track the result. We will also take advantage of the @tailrec annotation which tells the compiler to expect tail recursion and throw an error if that is not the case.

def reverse_tail2(s: String): String = {
 @scala.annotation.tailrec
 def impl(ss: String, r: String): String = {
   if (ss == null) return null
   if (ss.tail.isEmpty) return ss.head + r
   impl(ss.tail, ss.head + r)
 }
 impl(s, “”);
}