Functional programming in Scala
Functional Programming focuses on using functions as the basic units to construct the whole program. As a first step to get an insight into Functional Programming in scala, I summarize here some functional programming techniques in the scala language to build the functions.
1. Local functions
Like local Variables, local Functions can be defined inside a function
import scala.io.Source
object LongLines {
def processFile(filename: String, width: Int) {
def processLine(line: String) {
if (line.length > width)
println(filename +": "+ line)
}
val source = Source.fromFile(filename)
for (line <- source.getLines())
processLine(line)
}
}
2. Function values
You can define a function without name (which is called a function literal) and then pass them around as a value after compiled (which is called a function value). You can store a function value in a variable, since a function value is also an object.
*A function literal without name*
(x: Int) => x + 1
*Store a function value in a variable*
scala> var increase = (x: Int) => x + 1
increase: (Int) => Int = <function1>
3. Partially applied functions
A partially applied function is an expression in which you don’t supply all of the arguments needed by the function. Instead, you supply some, or none, of the needed arguments.
scala> def sum(a: Int, b: Int, c: Int) = a + b + c
sum: (a: Int, b: Int, c: Int)Int
*Supply 2/3 arguments*
scala> val a = sum( _: Int, 2, 3 )
a: Int => Int = <function1>
*Supply 1/3 arguments*
scala> val b = sum( _: Int, _: Int, 3 )
b: (Int, Int) => Int = <function2>
*Supply 0/3 arguments*
scala> val c = sum _
c: (Int, Int, Int) => Int = <function3>
4. Closures
A closure is a function value of a function literal with free variables
*A free variable*
scala> var more = 1
more: Int = 1
*A closure*
scala> val addMore = (x: Int) => x + more
addMore: (Int) => Int = <function1>
*Call a closure*
scala> addMore(10)
res17: Int = 11
5. Curried functions
A curried function transform a traditional function with one list of multiple parameters to multiple lists of one parameter.
*A traditional function with one list of multiple parameters.*
scala> def traditionalSum(x: Int, y: Int) = x + y
traditionalSum: (x: Int,y: Int)Int
scala> traditionalSum(1, 2)
res4: Int = 3
*A curried function with multiple lists of one argument*
scala> def curriedSum(x: Int)(y: Int) = x + y
curriedSum: (x: Int)(y: Int)Int
scala> curriedSum(1)(2)
res5: Int = 3