Skip to main content

Functional Programming in Scala: Getting Started

Functional Programming is becoming increasingly popular because it offers an attractive method for exploiting parallelism for multicore and cloud computing. As the name indicates functional programming focuses on the functions. A functional programming language is one which does not have mutable variables, assignments, loops, and other imperative control structures. Some of the important functional programming languages are 
  • Lisp, Scheme, Racket, Clojure
  • SML, Ocaml, F#
  • Haskell (full language)
  • Scala
  • Smalltalk, Ruby (!)
REPL(Read-Eval-Print) 
An interactive shell or REPL lets one write expressions and responds with their value. Scala REPL can be started by typing

>scala
For example;
>scala 23+34
57

>scala def length = 10 
length: Int
>scala def breadth = 20
breadth: Int
>scala length*breadth
200

Parameters and Return type in def
Definition may consist of parameters. Sometimes return types are also specified in the definition. For example

scala> def sum(x:Int, y:Int) = x+y
sum: (x: Int, y: Int)Int
scala> sum(2,3)
5
Function parameters come with their type, which is given after a colon. For example;

def isDevisible(x:Double, y:Int): Boolean = 

Evaluation strategies: Call-by-value & Call-by-name
Call by name and call by value are two types of evaluation strategies employed in functional programming. In the case of call by value, the interpreter reduces function arguments to values before rewriting the function application. But for call by name evaluation, one could alternatively apply the function to unreduced arguments. 
Both strategies reduce to the same final values as long as
  • the reduced expression consists of pure functions, and 
  • both evaluations terminate.
Consider an example:
sumOfSquares(2, 3+4)           sumOfSquare(2, 3+4)
sumOfSquare(2,7)               square(2) + square(3+4)

square(2) + square(7)          2 * 2 + square(3+4)
2 * 2 + square(7)              4 + square(3+4)
4 + square(7)                  4 + (3+4) * (3+4)
4 + 7*7                        4 + 7 * (3+4)
4+ 49                          4 + 7 * 7
53                             4 + 49
                               53


Evaluation of the function sumOfSquares which computes the sum of the squares of the arguments is explained above. The left one corresponds to call by value method and the other illustrates the call by name method.
Scala normally uses call-by-value, but if the type of a function parameter starts with => it uses call-by-name.

Conditional Expressions 
Conditional expression if-else is used in scala to choose between alternatives. 
Eg;

def isPositive(x: Int) = if (x >= 0) true else false

x >= 0 is a predicate, of type Boolean. Boolean expressions b can be composed of
Constants (true, false),Negation(!), Conjunction(&&), Disjunction(||) and of the usual comparison operations.


Blocks in Scala
It is a good discipline in functional programming to arrange the code into separate blocks so that it avoids the name space pollution and becomes more readable. Every block of code will have a start and end braces. Consider the below given example;

val x = 3
val y = 1
def sum(x: Int , y: Int) = x + y
val res = {
  val y =sum(x,1)
  y * y
}
  • The last element of a block is an expression that defines its value.
  • Blocks are themselves expressions; a block may appear everywhere an expression can.
  • The definitions inside a block are only visible from within the block.
  • The definitions inside a block shadow definitions of the same names outside the block.
     
Semicolons
In scala, for a single line of code, use of semicolon is optional. But when there are more than one statements in a line, they need to be separated by semicolons.

eg:  val x = 23; x + 1 

One problem with semicolon convention is to write codes that span several lines. There are two alternatives to solve this problem. 
    1. Write the multi-line expression in paranthesis.
    2. Write the operator of the expression in the first line.
These are some basics of principles of functional programming in Scala. Some good references of the topic are given below:
1. Structure and Interpretation of Computer Programs. Harold Abelson and Gerald J. Sussman. 2nd edition. MIT Press 1996. Download 
2. Programming in Scala. Martin Odersky, Lex Spoon, and Bill Venners. 2nd edition. Artima 2010.
3.Scala for the Impatient. Cay Horstmann Download

Comments

Popular posts from this blog

Backbone.js - An Introduction

Backbone.js is a lightweight JavaScript library that adds structure to your client-side code.  Developers commonly use libraries like Backbone.js to create single-page applications (SPAs).  What is a Single-Page-Application? A single page Web App is a website that attempts to recreate the experience of a native desktop or mobile application. On a Single Page Web App you are less likely to see page refreshes, the browser navigation within the app is often overridden and  there will usually be some offline capabilities. To a user their interaction with a Single Page Web App will be almost identical to how they interact with a full native application. Backbone has many advantages over other js frameworks. Backbone is mature, popular, and has a number  of plugins and extensions available that build upon it. It has been used to create non-trivial applications by companies such as Disqus, Walmart, SoundCloud and LinkedIn. Backbone organizes its whole code under t...

Elements of Programming in Scheme

A powerful programming language provides a framework to interpret our ideas of processes. It generally combines small procedures to complex ones. Usually there are three steps to accomplish this. primitive expressions , which represent the simplest entities the language is concerned with, means of combination , by which compound elements are built from simpler ones, and means of abstraction , by which compound elements can be named and manipulated as units. Some very basic ideas in manipulating with the data are given below. Expressions   A very simple expression is a number. Simple expressions are combined to form complex ones. For example:                   (+ 2  3  4) is an expression where + is the operation and 2,3,4 are the oparents. The expression can be made more complex by combining simple expressions as given below:              ...

Abstraction Using Higher Order Procedures

Procedures are, in effect, abstractions that describe compound operations on numbers independent of the particular numbers. Yet even in numerical processing we will be severely limited in our ability to create abstractions if we are restricted to procedures whose parameters must be numbers. Often the same programming pattern will be used with a number of different procedures. To express such patterns as concepts, we will need to construct procedures that can accept procedures as arguments or return procedures as values. Procedures as arguments Procedures are often used as the arguments of an another procedure. This provides a higher level of abstraction in programming. For example consider a procedure to find out the sum of squares of numbers between a range. The procedures inc and square are used as the arguments of the procedure sum, which is generalised as follows.                 (define (inc...