Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional Programming vs OOP [closed]

I just looked up a few examples/definitions of the differences between Functional Programming and OOP. I found one definition that I thought was interesting and I understood the OOP part but needed a bit of clarity/example for the Functional Programming part.

"Functional programming tends to reuse a common set of functional utilities to process data. Object oriented programming tends to colocate methods and data in objects."

What is meant by functional utilities? I get OOP in general and so that definition makes sense to me. Thanks in advance

like image 257
don Avatar asked Mar 03 '23 02:03

don


1 Answers

There are a few core utility functions that really make functional programming feel different: map, filter, fold (also called reduce), and unfold. In addition, most functional languages make use of generic data structures that can be targeted by these operations, and data is represented by simpler types. Whereas in object-oriented programming you might have a MovieList object that contains Movie objects and has methods that iterate over or operate on those movie objects, you're more likely to just have the Movie objects in a functional language and use them in the context of a List of Movie data structure.

For example, imagine that you wanted the uppercase version of the movie title in an OO language. It might look something like this:

// This would, presumably, be a method on MovieList.
public List<String> getUppercaseTitles() {
    List<String> uppercaseTitles = new ArrayList<>();
    for (Movie movie : this.getMovies()) {
        uppercaseTitles.append(movie.getTitle().toUpper()); 
    }
    return uppercaseTitles;
}

In a functional language, a similar operation is more likely to look like this:

uppercaseTitles :: [Movie] -> [String]
uppercaseTitles movies = map (toUpper . title) movies

In other words, instead of giving step by step directions with a for loop and imperative method calls, you are declaring that uppercaseTitles consists of a map of the composition of two functions (toUpper and title) to a list of movies.

like image 60
asthasr Avatar answered Mar 12 '23 02:03

asthasr