2

Can any one please explain the difference between a function and a method in Functional Programming aspect.

I am asking this question with a case study of Scala

We have 2 things noted down i.e a function and a method which does the same thing

Method

def add(x:Int, y:Int):Int = x + y

Function

val addFunc:Function1[Int, Int] = (x,y) => x + y

We can see that both of them does the same thing i.e addition of 2 Integers.But we get some additional properties with a function.

  1. As this is a function this will be treated as a first class object like Double,Float etc that can be passed as a value to any other function or a method

  2. We can probably store this function within a datastructure such as alinked List or a HashMap

  3. This is a perfect example of immutability and preserves referential transparency from the functional programming world i.e I can gaurantee that called this function N times I will always get the same result as this do not have any side effects.

  4. This can be passed to a higher order function such as a map or a reduce and can do N no of things

  5. This is a type dependent as it clearly specifies its type i.e (Int => Int)

Can anyone explain in detail some other benefits that a function can provide as compared to a method from an imperative programming language?

Eugene Loy
  • 12,224
  • 8
  • 53
  • 79
  • 1
    [What is the difference between a method and a function](http://stackoverflow.com/questions/155609/what-is-the-difference-between-a-method-and-a-function) – Sergii Lagutin Nov 18 '14 at 11:31
  • 1
    Or more specifically: http://stackoverflow.com/questions/2529184/difference-between-method-and-function-in-scala – Gabriele Petronella Nov 18 '14 at 11:41

1 Answers1

2

There aren't many other advantages, but the fact that in functional languages functions are first class citizens (while methods aren't) is a big deal.

If a function is passable to other functions, you get the possibility to create higher order functions like map or filter or reduce, which are much more concise than other non-functional approaches.

For example, let's sum the squares of all the odd numbers in a list:

In a non functional language you get something like (note: this is pseudocode):

List[Int] list = new List(1, 2, 3, 4, 5, 6, 7, 8, 9);
Int acc = 0;
for (Int x: list) {
  if (x % 2 != 0) {
    acc += Math.Pow(x, 2);
  }
}

in functional Scala code you have:

val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
val acc = list.filter(_%2!=0).map(x=>x*x).reduce(_+_)

which is far more concise even in just this toy example. See how we are passing functions (odd, square, sum) to other functions (filter, map, reduce).

Note that this doesn't give you new powers: you can't do things that are impossible to do in other non functional ways, it's just easier to do it ;)

Diego Martinoia
  • 4,592
  • 1
  • 17
  • 36