What is Functional Programming from a student’s point of view part-I
Hello all! I love to take notes when i’m studying a topic. Currently i’m at Trendyol Data Talent Bootcamp and studying data engineering.So i’d like to share my thoughts and learning adventure about Data Engineering, Functional Programming, Scala etc.
This is my studybook, enjoy ! :)
What is Functional Programming ?
What i understand about functional programming is that programming paradigm that much similar to actual math. Most of us learning programming with imperative programming language such as, C, Java, C#, Python etc. Functional programming is a declarative programming. So what are the difference ?
Imperative Programming
The definition of imperative programming in wikipedia is “programming paradigm that uses statements that change a program’s state.”
Simply we have to command everyting to computer step by step.
Functional programming on the other hand, “programming paradigm where programs are constructed by applying and composing functions”
In this part of my functional programming in scala advanture i’d like to share my study about these concepts such as , Pure Function, Side effet, Referential Transparency, and immutability
Side Effect
If something you do will change any other thing its local scope, it can be named by side effect in computer science.
x = 2
def add(y):
return x + y
In this python example, we can see that add function has side effect because the function changes the global x variable but normally not its scope.
In my opinion, if our code have side effects it’d be hard to debug or maintain code. If we avoid it would be much easy to fix a bug or read the code because
the job of functions is only about its scope. Simply, we can modify just the function itself nothing else.
Pure Function
Pure function is a function that has no side effect. Also pure function must be return the same value for the same input.
def add (x,y):
return x+y
No matter how many time invoke the add function with same input like 2,3 each time the add function returns 5. Because it’s pure function and it doesn’t change any other variable out of scope.
Referential Transparency
There is a great answer in stackoverflow if anyone interest further reading
In computer science, referential transparency is a concept that if we replace the function or variable with its value and the program will work same as before It’s referential transparent.
def multiply(x,y):
return x*yadd(3,multiply(5,3)) == add(3,15)
These two functions return the same value, because multiply function is referencial transparent.
Immutabilty
Everyting change! Except immutable things. I really don’t get the benefits of immutability at the beginning. After a week still i’m not sure %100 percent.
But i did some research and now i know a little bit more.
Immutability like stability, assure operations give the same result under same circumstances. This would code more predictive.
Immutabilty is also very important in Data Engineering. If somethings goes wrong with the database there is no come back. That’s why we shouldn’t modify the original data directly, just make a copy of it.
My Scala Notes
Unit : subtype of AnyVal. Unit has only one value type , and it’s like void in Java.
(like println() function)
yield: with yield keyword , function returns the finale result of iterations
LOOPS in scala
val with_yield = (for ( i <- 1 to 10) yield i)val without_yield = (for ( i <-1 to 10) println(i))
This code will works but without_yield we can’t assigned to value the final result of that iteration.
Basically this loop prints the loop but yield nothing without yield keyword.
Fooreach loop
val array = (1 to 10).toListfor (i <- array ) println(i)
Functions
Functions are expressions that have parameters, and take arguments.
val a_function = (x:Int) => x+1def b_function(x:Int) = x+1def c_function(x:Int) =
{
x+1
}
all functions are valid.
In scala there is a return keyword like most of the other programming language but even we can return the value without the return keyword
if we want to use return keyword we must define the returning type of this function like this (we don’t have to use curly bracket in this definition, what a flexilibity is this!)
In my opinion, the variety of written form quite diffucult for a new learner like me. But in time, it’d be a much better way to implementing code in diffrent cases.
Collections
Range
val a_range = (1 to 10)
we assigned a number sequence between 1–10 in a_range. This is a immutable Range Inclusive class in scala.
We can covert this sequence to array or list
a_range.toList or a_range.toArray
Arrays
Array is a typical data structure just like in other programming languages, we need to defined array size in definition and can’t change it.
val array = new Array[String](4)orval array = Array(1,2,3,4,5)
we can acces an element and update in array like
array(0) = “new value” or array.update(0,”New value”)
Lists
List is basically immutable linkedlist. Comparision to array, list size can be change.
val a_list = List(1,2,3,4,5)
or
val a_list = 1::2::Nil
So what is Nil ? Nil is extending from List[Nothing], thus it’d be way to create an empty list in scala.
Adding a new element to immutable list
We can’t add a new element in an immutable list :( Because, list is immutable and can not be change. So what should we do ?
I think there is better way to add a new element in a collection in scala like, ListBuffer -which is mutable — etc.
But if we really want to add an element in immutable list basically we create an empty list then adding this empty list to another list with another element.
That way, we create another list and copy the values from old list.
val empty_list = List.empty[String]val new_list = "new value"::"other new value"::empty_list
val cities = "AnkArA":: "İzMir"::"İstAnBuL"::Nilval capitalize_cities = cities.map(x=> x.toLowerCase.capitalize)
Cities values are not correct form we can get in shape these values and store in another list with map function. Note that this map is a list method
that perform an operation in each element in list.
Map
Map is similar to python dictionary, or java hashmap. We can create a collection that stores values in key -> value format.
val citymaps = Map(
1 -> "Ankara",
2 -> "İzmir",
3 -> "İstanbul"
)println(citymaps.get(2)) get returns a Option(value) if the key exist in map. I want to cover Options in another article :)println(citymaps.contains(2))
FoldLeft and FoldRight
Reverse without reverse function
def reverseWithFold(arr:List[Int]):List[Int] = {
arr.foldLeft(List[Int]())
{ (acc,elem) => elem::acc }
}
Simply, reverseWithFold function takes list arr as an argument and return a list.
foldLeft combines all element and produce a final output. The explantion of what’s going on above is foldLeft start with an initial value, and iterate left to right all elements and accumulate them. Our head element of list is 10 and initial value is empty list. Take the empty list, and 10 as a elem
First iteration is -> 10 :: Nil
Second iteration is -> 9::10 ::Nil
Third iteration is -> 8::9::100:: Nil
reverseWithFold(List(10,9,8,7,6,5,4,3,2,1)) => 1,2,3,4,5,6,7,8,9,10
Thanks who read all of my notes i hope you enjoyed! Please feel free to give me any feedback or ask any question. Let’s see you guys in part 2 :)