<p>This is a very broad question, so I'm going to point you to a couple places and then give a really short explanation. </p>

<ul>
<li>Wikipedia on paradigms: <a href="https://en.wikipedia.org/wiki/Programming_paradigm" rel="noreferrer">https://en.wikipedia.org/wiki/Programming_paradigm</a>

<ul>
<li>I'm linking to the main article, but linked at the bottom you should definitely check out the "Comparison" article as well as the specific sections and links to functional and OOP stuff.</li>
</ul></li>
<li>this SO post is pretty decent, <a href="https://stackoverflow.com/questions/552336/oop-vs-functional-programming-vs-procedural">https://stackoverflow.com/questions/552336/oop-vs-functional-programming-vs-procedural</a></li>
</ul>

<hr>

<p>I think it's important to have the right mindset about paradigms: At the end of the day, they're a tool to help you organize a thought process around code. They all let you accomplish the same tasks.</p>

<p>In general, nearly every language or environment today is 'multi-paradigm'. Even Java (which is famously OOP because everything is required to be in a class) is written in a style that blends imperative and procedural paradigms with OOP. More recently, Java includes more and more elements that are in the functional style.</p>

<p>When in comes to functional vs OOP, there's one big thing that comes to mind.</p>

<p>Being "stateless" or having "state"</p>

<p>State means that you have some stored properties or information, like the name of a sprite, or a display where you output information.
In a functional world, especially one that tries to be "pure", you're mostly going to be dealing with composing (or chaining) functions together. The goal is to have a function, say <code>compute_something(an_object)</code> that needs only the information passed into it (arguments) and nothing else - i.e. It has no "state". It will then return a new value, and not modify or mutate it's input. 
In the OOP world, it's common to think of an object having state, it's information about itself and how it interacts with the world. You might do something like <code>object.compute_something()</code>, where <code>compute_something</code> is a property (a function) tied to that object, and by calling it, you modify some property of that object.</p>

<p>One common example of this is sorting a list. In a functional paradigm, you'd probably do <code>sorted_list = sort(some_list)</code>. While in an OOP paradigm, you'd likely do <code>some_list.sort()</code> and the next time you use <code>some_list</code> it will be sorted.</p>

<p>Form this there are sometimes other differences, like how difference languages treat "types" of data, but things can get muddied quickly. </p>

<hr>

<p>To answer your original question about projects: It really is hard to say. You could conceptualize a Unit conversion app as having a bunch of objects (like one for each type of measurement system), or since it's "mathy-" you could just as easily conceptualize as a simple function with a lookup table for various conversion rates. In reality the paradigm will depend on the environment that you're working with as much as it will depend on the theoretic structure of code.</p>

CC BY-SA 3.0
2017-08-09T09:16:26.740Z
Interesting. I had not thought of some of the things you pointed out. Thanks
ItamarG3
CC BY-SA 3.0
2017-08-11T00:17:36.030Z
“While in an OOP paradigm, you'd likely do some_list.sort() and the next time you use some_list it will be sorted.” No. With an **imperative** paradigm, you'd do `sort(some_list)` (procedural) or `some_list.sort()` (OO) to change `some_list`. OO vs procedural is orthogonal to imperative vs functional. In functional OOP, you'd do `let sorted_list = some_list.sort()`.
Gilles 'SO- stop being evil'
CC BY-SA 3.0
2017-08-09T09:09:42.230Z
2017-08-09T09:09:42.230Z
Cycomachead
<p>As I read your post, I see your question as simply this:</p>

<blockquote>
  <p>where might I find a thorough comparison between the two [OOP and FP], which can
  explain which should be used for some kinds of tasks\projects?</p>
</blockquote>

<p>The best explanation I have seen is in the context of the Programming Languages MOOCs offered through Coursera modeled after <a href="http://courses.cs.washington.edu/courses/cse341/17sp/" rel="noreferrer">this course at UW</a>.</p>

<p>The class works through, in order, a statically-typed functional language (ML), a dynamically-typed functional language (Racket), and a dynamically-typed object-oriented language (Ruby). Since this is an upper-division course and students presumably are somewhat familiar with it, Java is thrown in for comparisons when relevant as a statically-typed objected-oriented language.</p>

<p><strong>If you want to find a thorough comparison, build projects with each approach, spending time to learn the relevant nuances of FP and OOP along the way.</strong> There is no chart or tutorial that can substitute for this work; it simply takes time and practice. Based on my experience, the work of this course will not disappoint. There are short mini-lecture videos, excellent reading notes, and challenging homework assignments all available for free.</p>

<p>At the end of the course, the professor does an excellent job breaking down OOP v. functional decomposition. By the time you reach the end, you will have a clear picture as to how these approaches differ, where their relative strengths and weaknesses like, and when/how to apply each paradigm to a particular problem.</p>

CC BY-SA 3.0
2017-08-09T15:36:14.610Z
I disagree with you that you will learn about *"how these approaches differ"* - they don't differ in any meaningful way.  They are orthogonal concepts from the start. It's like saying that you will learn how *tennis* differs from *clay* (of which the court is made), or how *paintings* differ from *paper*.
Ben I.
CC BY-SA 3.0
2017-08-09T15:39:57.930Z
@BenI. I'm not enough of a programming languages expert to speak with my own authority on such a matter, but I have a feeling the professor sees things differently. The end of the course dives in to how each approach takes fundamentally opposite approaches to program decomposition. From the lecture notes: "We show that the two approaches [OOP and FP] largely lay out the same ideas in exactly opposite ways." https://courses.cs.washington.edu/courses/cse341/17sp/unit8notes.pdf
Peter
CC BY-SA 3.0
2017-08-09T15:51:00.087Z
In that case, my disagreement is with the professor. Perhaps he overstated his case? The sentence that you have quoted would seem to be disproven by the existence of the many functional, object-oriented languages.
Ben I.
CC BY-SA 3.0
2017-08-09T17:05:15.147Z
@nocomprende Your statement is beautiful, but I suspect it is ultimately more poetic than it is meaningful. Godel is talking about the limits of *provability*, which is simply unrelated to the notion of whether various engineering philosophies can play nicely with one another.
Ben I.
CC BY-SA 3.0
2017-08-09T15:20:43.993Z
2017-08-09T15:20:43.993Z
Peter
<p>It is difficult to put this into a form that inexperienced undergraduate students will appreciate, but well...</p>

<blockquote>
  <p>"It is commonly the case with technologies that you can get the best insight about how they work by watching them fail" - Neal Stephenson, <em>In the Beginning was
  the Command Line</em></p>
</blockquote>

<p>Since OOP is the 500lb gorilla of the programming world and FP the relative upstart this comparison might be a bit skewed for want of data points. However two prominent failure cases come to mind.</p>

<h2>1. Data Interchange</h2>

<p>The Sun God Microsystems bestowed upon the Paladin Knights of Programmingdom his Commandments etched into tablets of purest silicon for posterity and from whence His disciples founded the Church of Java. Any who were so foolish as to claim that these commandments from on high were a Pact with the Devils of Performance and Popular Sintax bastardizing the pristine purity of Smalltalk were denounced as heretics. And the proselytizers spread their faith unto the remotest corners of the kingdom.</p>

<p>So yeah, people started using OOP for everything. But there was (at least) one arena where this failed entirely: IPC. Exchanging data across the boundary of threads/machines/networks/languages was an issue. Exactly how much of an issue can be inferred from enumerating some of the (many) attempts at solving it in an OO fashion that litter the scrapheap of history: CORBA, RMI, WSDL, DCOM... and also from the extreme proliferation of using plain ol data generally in the form of XML (as opposed to using XML-RPC).</p>

<p>So now people still do this, but generally we use transport mechanisms that are <em>stateless</em> (like HTTP) and over them we send language-agnostic data (sexprs, XML, JSON). So in structuring intercommunicating <em>systems</em> FP won because dealing with state is hard enough on its own but becomes an order of magnitude harder when you add threads, then another order of magnitude (or two) harder when you add inter-machine communcations and another order of magnitude (or more!) harder still when you have many-to-many communications with needs for eventual consistency or accurate chronological ordering of events. In fact, just thinking about it enough to write that last bit raised my blood pressure to dangerous levels.</p>

<p>Which is not to say that people don't use OOP in that space at all anymore, but it's not super common and the search to find the Great-OOP-Protocol-that-Makes-it-EZ is a pursuit more easily compared to <a href="https://en.wikipedia.org/wiki/Cold_fusion" rel="nofollow noreferrer">cold fusion</a> or the <a href="https://en.wikipedia.org/wiki/El_Dorado" rel="nofollow noreferrer">Lost City of El Dorado</a> (no VC funding for you!) than trying to create the next megahit social networking app (\$\$purr\$\$).</p>

<h2>2. Games Programming.</h2>

<p>Programming games in FP is <a href="http://prog21.dadgum.com/23.html" rel="nofollow noreferrer">certainly possible</a>, but not necessarily recommended. And this goes beyond lack of libraries and middleware or the need to squeeze as much out of the hardware as possible: when my level 6 Half-Elf Berserker bashes an orc with her Hammer of Doom I expect that orc to be the same orc minus 3D6 hp not a new orc with a different hp value than the old one. The problem is that games deal generally with two different entities: <em>things</em> and <em>rules</em> about the interaction of those things <em>as they change over time</em>. No one wants to go all War Games and watch a supercomputer <a href="https://www.youtube.com/watch?v=F7qOV8xonfY" rel="nofollow noreferrer">play itself at tic-tac-toe</a> until it learns the futility of nuclear war. OOP <a href="https://ericlippert.com/2015/04/27/wizards-and-warriors-part-one/" rel="nofollow noreferrer">sucks at modelling rules</a> (which FP excels at), but OOP is <em>great</em> for modelling how reified things <em>change over time</em>.</p>

<p>Anyways, as I said at the beginning I'm not exactly sure how I'd go about making all of this accessible to CS undergrads (based on my memory of what I and my peers were like when I was one). But I think looking at two high profile failures is a good place to start.</p>

<p>Bottom line, as the other answers have said they are extremely different mental models. Anytime you try to use one that doesn't easily map to the problem domain you're going to have issues. So illustrating some of those domains with how one or the other is a more natural fit (and my examples above of shoving square pegs into round holes) and why might be the best way to approach the topic.</p>

CC BY-SA 3.0
2017-08-09T18:53:45.400Z
Your history is backwards. Object Oriented programming is the newbie here. FP predates the earliest proto-OO language by a decade. LISP, a functional language based on Church's Lambda Calculus, was the second high-level programming language ever created. It came out just 2-3 months after FORTRAN (the oldest high level programming language that exists).
Ben I.
CC BY-SA 3.0
2017-08-09T23:38:16.630Z
@BenI. I'm aware of the chronology. But in terms of mindshare in the lifetimes of undergraduate students (last ~20yrs) OOP has been utterly dominant. As programming and computer science are rapidly growing, a decent subset (majority?) of persons in the craft came of age in the Javassic Era and are just now being exposed to what LISP and Erlang (and ML and Haskell) have been doing for decades.
Jared Smith
CC BY-SA 3.0
2017-08-10T12:01:35.687Z
Regarding your games programming argument: [John Carmack taught his son game programming in Racket](https://twitter.com/id_aa_carmack/status/635839636754038784?lang=en), a LISP dialect.
ComicSansMS
CC BY-SA 3.0
2017-08-10T15:07:50.593Z
@nocomprende inexact metaphors are always stickier than exact but dry technical discourse :D
Jared Smith
CC BY-SA 3.0
2017-08-11T20:11:53.797Z
I don't quite understand what you are getting at with the rant (is it a rant?) about Java.  OOP was around for quite a while before Java, and I don't recall any controversy over whether Java's flavor of OOP was good when compared to Smalltalk.  In any case, Java was more a take on C++ than it was on Smalltalk.  There _was_ serious controversy over C++, but the controversy I remember came from C programmers.  Still does come from C programmers, now that I think of it.
Wayne Conrad
CC BY-SA 3.0
2017-08-11T23:47:27.613Z
@WayneConrad what I'm getting at with my not-rant is that Java was a juggernaut the left it's mark on almost every corner of Programmingland. Many people (not the least of which were Sun's marketing department) hailed it as the One True Language to Replace All Others. Except that it wasn't. The fact that it wasn't quite low-level enough to displace C in some domains and not quite high level enough to replace scripting languages in others doesn't make Java good or bad. In fact, the social-phenomenon aspect makes it rather hard to assess Java simply on its own merits.
Jared Smith
CC BY-SA 3.0
2017-08-11T23:51:07.883Z
...con't so you can't just talk about OOP without talking about Java which not only popularized many OOP concepts but made them *mandatory* knowledge for working programmers. I may not like it, but denying the reality would be foolish in the extreme. Simula didn't do that, smalltalk didn't do that, python didn't do that. Neither did C++ as you point out: people could and did just keep writing C if they wanted to. Java did that. Or more precisely, Sun's brilliant and insanely expensive marketing campaign did that.
Jared Smith
CC BY-SA 3.0
2017-08-09T17:44:09.417Z
2017-08-10T13:45:39.560Z
2017-08-10T13:45:39.560Z
Jared Smith
<p>Truth be told you will never truly understand the difference until you actually learn and use both a functional and an object oriented language. I say that as someone who has learnt both object-oriented languages (C#, C++, Java) and functional languages (Haskell).
I will however attempt to explain the crux of it.</p>

<p>My answer will be looking mostly at functional programming from an object-oriented point of view, as the features of object oriented programming are already very heavily documented due to its popularity whereas the features of functional programming are much more scarcely documented.</p>

<hr>

<p>Firstly imagine a computer language as a tool (or a collection of tools).
Every tool in the world has a particular purpose or a set of tasks that it's good for, and the same is true of languages.</p>

<p><strong>Functional languages</strong> tend to work better for problems that involve data-processing and deterministic processes. As such they are liked by scientists and mathematicians who can think in terms of pure data and algorithms.</p>

<p><strong>Object oriented languages</strong> are better for modelling complex interacting systems. They are preferred by businesses because of their ability to mediate complex tasks and by game developers because of their usefulness in modelling the world.</p>

<p>They can of course be used for other things, but these are typically what the approaches are centred around.</p>

<hr>

<p>At the language level the crux of the matter that sets functional languages apart are these factors:</p>

<ul>
<li>They shun local state (with caveats).</li>
<li>By extension they forbid functions from having side-effects (functional 'purity').</li>
<li>Implicit type inference</li>
<li>The dependence on 'lists'</li>
<li>The use of sum types</li>
<li>The use of type classes (or 'contracts')</li>
<li>Implicit currying</li>
</ul>

<p>(Note that these are not all completely necessary for something to be considered a functional language, but they are features that are commonly associated with functional languages because they can be found in a wide variety of functional languages, particularly the most popular ones.)</p>

<p><strong>State:</strong></p>

<p>In a functional language, values are created and they do not change - instead the old value is destroyed and a new value is created. At face value this seems a bit crazy, but in reality this abolition of state (with caveats) is only at the language-level, the compiler translates the source code into machine code that still has a concept of state, which somewhat breaks the illusion and makes this notion a bit less shocking.</p>

<p>The caveats I mentioned are that there are ways to emulate state in one way or another. One way of doing this is by maintaining the state as a function variable and another way is by using a construct called the 'State monad'.</p>

<p><strong>Purity:</strong></p>

<p>Equally, although all functions must be 'pure' (i.e. must not have side effects), there are various monads that allow there to still be side effects without breaking the laws of the language. Monads are how any kind of IO (file IO or terminal IO) is made possible. Essentially, the behaviour of the program is bound to the monad through functions that act a a means of sequencing - the monad then represents a list of actions that describe the translation and processing of the data.</p>

<p><strong>Type inference:</strong></p>

<p>(This is not found in all functional languages and may sometimes be found in certain object-oriented languages such as C# and C++.)</p>

<p>It is where the compiler is able to evaluate the type of an expression by looking at the types of the values and functions in the expression and deducing what the valid results could be. If there is only one unambiguous match, the compiler is able to infer the type, making many definitions as simple as the values and functions themselves - no explicit typing involved. In other cases, there is ambiguity and some type notation must be used to disabiguate the result.</p>

<p><strong>Lists:</strong></p>

<p>Furthermore, the core data type of functional languages is a kind of singly-linked list often referred to simply as a 'list'. This takes the role of the basic collection datatype and is used how arrays and dynamic arrays are used in many object-oriented languages.</p>

<p>Another significant difference is the language-level support for sum types. Sum types are like objects with different constructors, and work <em>sort of</em> like inheritance in object oriented languages. That is, the type itself can be an abstract concept (e.g. a tree) and the constructors for it can represent different values of that concept (e.g. and empty tree, a leaf node and a branch node). It is because of this that tree data types are very easily represented in functional languages, and as such they are well-liked for solving mathematical tree-related problems and for implementing parsers and/or compilers.</p>

<p><strong>Type Classes (or 'contracts'):</strong></p>

<p>Type classes are similar to interfaces in object-oriented programming but have the distinction that they are not implemented at the time the datatype they are applied to is defined, they are implemented after the type has been defined. This means that they can be applied after the fact to datatypes that one does not 'own'.</p>

<p>Type classes are defined simply as a 'contract' that list a series of functions and/or values for which the obeying datatype must have an implementation. In effect the 'contract' states "any datatype said to implement this type class must provide an implementation for these functions".</p>

<p>For example there could be a datatype <code>addable a</code> (Where <code>a</code> is a type variable - a symbol standing in for an as yet undeclared type)  that specifies a function called <code>add</code> with the signature 'a -> a -> a' (a function accepting two arguments of the type represented by <code>a</code> and returing a value of the type represented by <code>a</code>). This loose definition means the <code>addable</code> type class can be implemented by many different data types, including <code>Int</code>, <code>Float</code> and any user-defined arithmetic type.</p>

<p><strong>Currying:</strong></p>

<p>(Note that not all functional languages support this, but it is much more commonly found in functional languages than in object oriented ones.)</p>

<p>Currying is a technique named after Haskell Curry (the same person for whom the language Haskell is named).
Currying means that a function is only bound to one argument and then returns either a result or another function accepting an argument. In functional languages, all functions are implicitly curried, which means that no function actually accepts more than one argument. This in turn means that when you write a statement like <code>add 3 5</code>, what actually happens is that the <code>3</code> gets bound to the <code>add</code> function, which then returns a function accepting a number, to which the <code>5</code> gets bound, and only then does that return a result.</p>

<p>This probably seems insane to someone not used to the idea, but it actually makes a lot of things much easier. For example there is typically a function called <code>map</code> which takes a function and applies that function over the contents of a list (much like a loop could do in imperative languages), and the ability to curry functions makes the definition of a the function passed to <code>map</code> very simple. If, for example, you wanted to add 5 to a list in Haskell, you could simply write <code>map (+5) list</code> - the <code>(+5)</code> takes the function <code>+</code>, binds it to the value <code>5</code> and returns a function taking a number and returning the result of that number <code>+ 5</code>.</p>

CC BY-SA 3.0
2017-08-10T08:12:00.113Z
I am afraid this answer conflates Functional Programming and Haskell. At the very least Type Inference, Type Classes and Currying are NOT a hallmark of FP.
Matthieu M.
CC BY-SA 3.0
2017-08-10T10:10:46.147Z
@MatthieuM. Could you give some examples of functional languages that do not have these features? Also I was under the impression that the majority of functional languages apply the principles of typed lambda calculus and use a hindley-milner type inference system.
Pharap
CC BY-SA 3.0
2017-08-10T10:45:22.173Z
Lisp? *(Not sure if it has currying)*
Matthieu M.
CC BY-SA 3.0
2017-08-10T10:50:55.547Z
@MatthieuM. Ok, I checked and Lisp does indeed not have currying, so I will mark that as a 'sometimes' feature (because it's still more prominent in functional languages than object oriented ones). That doesn't rule out type classes or type inference though. I suspect it's possible type classes are not considered a 'core' feature of functional languages, but I'm pretty sure hindley-milner type inference is because of the relation to typed lambda calculus which is partly what sparked the idea of functional languages in the first place.
Pharap
CC BY-SA 3.0
2017-08-10T10:57:39.777Z
Lisp is dynamically typed, so no type inference is necessary (or meaningful). Possibilities for making it statically typed are [discussed here](https://stackoverflow.com/questions/3323549/is-a-statically-typed-full-lisp-variant-possible).
Matthieu M.
CC BY-SA 3.0
2017-08-10T16:54:24.907Z
@nocomprende I just about understood the horse grooming joke thanks to google, but I don't understand the first sentence. No comprende, no comprende.
Pharap
CC BY-SA 3.0
2017-08-10T17:01:21.993Z
@MatthieuM. I shall mark that as also a 'sometimes' feature, but I believe it's a somewhat popular one that's typically considered to be a feature expected more from functional languages. Or at least [C2 seems to think so](http://wiki.c2.com/?TypeInference). I suspect this is due to the great influence of ML upon other functional languages.
Pharap
CC BY-SA 3.0
2017-08-10T17:44:23.520Z
@nocomprende I am aware of that saying and its application to computer languages. It's often applied to patterns too. (The bit I got hung up on was the word 'tale', which as far as I know is a synonym for 'story', which doesn't really fit the sentence.) Technically humans are animals. At any rate, this seems like an esoteric, slightly poetic tangent rather than a comment about the answer.
Pharap
CC BY-SA 3.0
2017-08-10T18:07:56.833Z
@nocomprende "I was just putting in a warning that we often need to take a step back from debates and consider carefully the basis for the whole question. " - _that_ is a fair point. What you had to say was valid, I think your earlier comments were just a bit too crypic at what they were getting at. (Either that or they made perfect sense and I'm just tired.) It's up to you whether you delete them or not, they might be considered 'too chatty' they might not be - I can't really say either way.
Pharap
CC BY-SA 3.0
2017-08-11T00:21:33.580Z
Currying is inherently possible in any functional language, but whether it's used has little relation with the design of the language. For example Standard ML and Ocaml have a very similar core, but SML favors tuples as function arguments while Ocaml favors currying. (“Favors” means that this is what the standard library uses and the compiler optimizes this case better.)
Gilles 'SO- stop being evil'
CC BY-SA 3.0
2017-08-11T00:23:06.387Z
“In a functional language, values are created and they do not change”. In a *pure* functional language. For example, Haskell does not allow values to change (or rather, it requires going through a monad); ML discourages mutable values; Lisp tends to use them a lot.
Gilles 'SO- stop being evil'
CC BY-SA 3.0
2017-08-11T00:24:53.710Z
Type inference is only very loosely connected to functional languages, in that the most advanced type systems tend to be implemented on functional languages. Lisp is statically untyped (singly typed if you want to get technical). Many imperative languages are statically typed.
Gilles 'SO- stop being evil'
CC BY-SA 3.0
2017-08-11T09:26:59.647Z
@Gilles "Note that these are not all completely necessary for something to be considered a functional language, but they are features that are commonly associated with functional languages because they can be found in a wide variety of functional languages, particularly the most popular ones."
Pharap
CC BY-SA 3.0
2017-08-09T23:08:24.777Z
2017-08-13T00:17:40.700Z
2017-08-13T00:17:40.700Z
Pharap
<p>Functional programming is all the rage nowadays. It relies on the illusion that stateless objects and immutable data structures will keep the bugs out. Which is of course nothing but a self-fulfilled prophecy.</p>

<p>Statelessness and immutability are the current Holy Grail and Golden Fleece, mostly because they allows to write junk code faster (a function will always return the same result regardless of the current state of the system, so once it's debugged we're pretty much safe, right?) and we don't know any better way of using these new shining CPUs (functional programming requires a lot more resources than plain old procedural / object oriented approaches - just look at the exponential growth of C++ compile time!).</p>

<p>Functional programming is easier and faster to write. It encourages to concentrate on generic and simple building blocks and follow a bottom-up path.<br>
On the other hand, it tends to become verbose and unmaintenable fast, what with the layers upon layers of progressively complexified functions you have to write.</p>

<p>With OOP you need at least some top-down approach. A general sketch of your final architecture before you can even start coding. After a couple decades of "extreme" and "agile" programming, the dreams of an easy way out of this initial planning are slowly starting to recede (after having cost an unknown but probably sizeable fraction of the world's GDP in failed projects and botched software). Now, with the shiny GAFAs as role models, functional programming is taking over as the new magical paradigm.</p>

CC BY-SA 3.0
2017-08-09T17:10:45.637Z
This is full of unsubstantiated opinions and reads more like a rant than an answer. Hype is orthogonal to utility: things can be anywhere in the matrix of sexy/boring and useful/superfluous.
Jared Smith
CC BY-SA 3.0
2017-08-09T21:55:16.207Z
I wouldn't say it's all the rage. The only popular 'functional' language I can think of is Rust, and that's more than just plain 'functional', it has OO characterists too - it's more of a hybrid. All the older functional languages are preferred by mathematicians and scientists (or people who like maths and science). Granted many OO languages have adopted pseudo-functional features such as lambda expressions, that doesn't necissarily make them interested in the functional paradigm, rather the implementors have seen a feature they liked and found a use for and adapted it to suit their needs.
Pharap
CC BY-SA 3.0
2017-08-09T23:30:34.447Z
@Pharap indeed, that's what I call whims of fashion. Templates in C++, stateless and immutable structures all over the web, JavaScript and Python being used as poor man's FP... Immutability and statelessness can be very appealing when dealing with concurrent processes (multithreading that has become mandatory since we started hitting the speed limit of a single CPU, or networking, after 30 years of calamitous efforts to synchronize data brokers), but still they are no silver bullets: costly, hard to read, relying on increasingly complex (and unreliable) tools to reach OOP performances.
kuroi neko
CC BY-SA 3.0
2017-08-10T00:06:41.360Z
@kuroineko I wouldn't knock templates because they can be incredibly useful and time-saving *in the right hands* (emphasis important), the ability to write them is certainly more useful for library writers than regular programmers though. I can understand the want for statelesness (it's more about the web's core principle of robustness), but I agree with JavaScript and Python creeping into territory they are unfamiliar with (functionalism).
Pharap
CC BY-SA 3.0
2017-08-10T01:26:32.127Z
@Pharap Even non-library writers can use templates for creating flexible data structures of their own. Getting deep into template metaprogramming is more something that would be relegated to library or framework code, admittedly, but the ability to delay type/etc. selection to the time of usage is incredibly useful for any programmer writing significantly complex C++ programs.
JAB
CC BY-SA 3.0
2017-08-10T01:54:53.317Z
@JAB They can do if the problem they are solving is well suited to generics (such as writing datastructures or arithmetic types), but those cases occur less frequently than the standard case for most programmers. Plus there's the same danger with templates as there is with programming patterns, and that's the "this is cool, let's make _everything_ a template" mentality. The danger doesn't come from the templates themselves, it comes from them being considered a cool thing to know - it attracts people who will learn _how_ to use them but not _when_ to use them.
Pharap
CC BY-SA 3.0
2017-08-09T11:21:30.607Z
2017-08-09T11:48:16.393Z
2017-08-09T11:48:16.393Z
kuroi neko
<p>There are beautiful answers to this question already here, and I will not try to reiterate any of the ground that has already been covered.  However, something important that I have not seen here so far is that comparing OOP to FP is not actually terribly meaningful.  It's a bit like comparing <em>glass</em> (the material) to <em>tables</em> (the furniture).  They each have properties that can be explored, but even if discussions of these properties can help you learn about them, the comparison itself doesn't actually tell you much about either.  Glass tables exist, and have the properties of both.  Similarly, Scala, Clojure, and Swift are languages that are <em>both</em> functional and OO.</p>

<p>A more meaningful comparison for functional programming is imperative programming.  The most popular languages in the world right now are all imperative<sup><strong>1</strong></sup>.  Imperative languages focus on mutable values and states, and are historically based on <strong>Turing Machines</strong>.  Functional languages are all about function calls and immutable constants, and are historically based on Church's <strong>$\lambda$-Calculus</strong>.  </p>

<p>The two mathematical systems were developed around the same time in order to solve the same question: <em>what is fundamentally computable?</em>  The <strong>Church-Turing Thesis</strong>, which was published before electronic computers existed, proved that the two systems were equally powerful, and further hypothesized that they could both compute any computable function, and that any <em>sufficiently complex system</em> could embody exactly this same computability power.</p>

<p>A more meaningful comparison for Object-Oriented programming would be... well, <em>nothing</em>.  The Object-Oriented philosophy, which is about grouping data with functions that govern that data, can be applied to any programming paradigm.  Object-Oriented programming is all about the <em>scope and membership</em> of functions and data.  It doesn't matter if the data is mutable, if the order of operations is defined, how data is stored, whether functions are mutable... if we are creating instances of data that are bundled with their own functions, the we have the kernel of object-oriented programming.</p>

<p><sup><strong>1</strong> - Only if you discount Excel, which is actually a light functional programming language, and is almost certainly used by <em>many more people</em> than any other programming language on earth.</sup></p>

CC BY-SA 3.0
2017-08-09T19:10:36.483Z
+1, You could compare object oriented to data oriented, though.
Daniel Jour
CC BY-SA 3.0
2017-08-09T19:11:15.453Z
The opposite of OOP would seem to be maintaining a separation between data and behavior.  (These opposites aren't mutually exclusive, though - I've seen programs that mix imperative *and* functional *and* OOP *and* separation of data and behavior - they just do different things in different places.)
Brilliand
CC BY-SA 3.0
2017-08-12T23:26:57.333Z
Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/63722/discussion-on-answer-by-ben-i-learning-fundamental-differences-between-function).
thesecretmaster
CC BY-SA 3.0
2017-08-09T14:31:58.217Z
2017-08-12T14:42:21.083Z
2017-08-12T14:42:21.083Z
Ben I.
<p>FP and OOP are both tools in the box, none of them is better or worse. The same way you would not ask whether to use a hammer or a screwdriver to put in a nail, you should not ask whether to use FP or OOP. </p>

<p>The question should be: what is the best way to solve your problem at hand?</p>

<p>OOP excels when you need to describe abstract objects with code (hence the name). Describing the abilities and features of a car is something FP is not made for, so choosing FP for this situation would be painfully complicated.</p>

<p>Vice versa FP excels when algorithms can be written as mathematical functions in the mindset of <code>f(x) -&gt; y</code> (more complex functions are also very much possible). Using OOP to describe the result of <code>square(x)</code> is possible but pointlessly complicated.</p>

<p>In modern programming FP is usually used when volumes of data need to be transformed. If you need to map from Z to Y by using the transformation function f, then you can very simply write that in code using FP, i.E. in Java like this:</p>

<pre><code>// equivalent of Yn = f(Zn)
List&lt;Y&gt; myYs = myZs.stream()      // for each z in Z
  .map(MyClass::f)                // transform y = f(z)
  .collect(Collectors.toList());  // and store y in a list
</code></pre>

<p>Doing the same in OOP would look something like this:</p>

<pre><code>class Z {
  private int myValue;

  public int getValue() {
    return this.myValue;
  }
}

class Y extends Z {
  static Y convertFromZ(final Z z) {
    // ...
  }

  @Override
  public int getValue() {
    return convertFromZ(super.getValue());
  }
}

List&lt;Y&gt; myYs = (List&lt;Y&gt;) myZs;  // &lt;-- really dirty hack
</code></pre>

<p>This makes it hopefully obvious why such a comparison chart does not exist: because those two are entirely different concepts.</p>

CC BY-SA 3.0
2017-08-09T13:25:49.897Z
Welcome to [cseducators.se]! that's a very useful overview and explanation. Thanks!
ItamarG3
CC BY-SA 3.0
2017-08-09T20:00:54.737Z
I would ask whether to use a nail or a screw, e.g.: http://www.popularmechanics.com/home/tools/how-to/a18606/nails-vs-screws-which-one-is-stronger/ .  OO vs FP is different in that it's possible (reasonable) to do both, e.g. making `x.square()` return a new object or writing a method `expr.calculated_type()` in a compiler.
Jonathan Cast
CC BY-SA 3.0
2017-08-09T13:22:38.367Z
2017-08-09T13:22:38.367Z
TwoThe
<p>I wouldn’t expect to find a comparison table because OOP and FP are not mutually exclusive concepts.</p>

<p>OOP is about encapsulating data in objects behind interfaces and using inheritance to build objects in re-usable pieces.</p>

<p>FP, however, is about not changing states or having side-effects.</p>

<p>You can have an OOP program with immutable objects. (You can <em>clone</em> an object, but you can’t change the state of an existing object.) You can have an OOP program where the methods have no side-effects.</p>

<p>You can have a FP program that encapsulates its data in objects behind interfaces and uses inheritance.</p>

CC BY-SA 3.0
2017-08-09T14:31:50.587Z
2017-08-09T14:31:50.587Z
Robert Fisher
<p>There are already several good answers, but I'd like to add the following.</p>

<p>Functional code is (at least in theory) more easily parallellized.  This is important because we've about hit the limit of how fast we can run integrated circuits.  (I know that's an oversimplification; I'm trying to keep it simple for the OP's audience's sake.)<br>
So, while you can't make the individual cores on your CPU run much faster, you <em>can</em> add cores to the CPU.  </p>

<p>Now let's think about a single large program.  Multiple cores will only speed up such a progrm if it can be broken up into independent "chunks" that can be parcelled out to individual cores.  And let's be clear about what "independent" means: no one chunk should have side effects that can affect any other chunk (and probably chunks should not depend on the output of other chunks).</p>

<p>This is an area where functional programming excels.  By contrast, trying to ensure object consistency across multiple threads or processes can be a nightmare.  Which is one reason there's a great deal of current interest in FP.</p>

<p>The downside is ... as Jared points out, in a game, in the FP paradigm, you'd likely maintain statelessness by having the "attack" routine return a whole new copy of the orc (or whatever enemy) under attack.  But:</p>

<ol>
<li>Reconstructing the entire orc is probably a non-trivial operation -- it's almost certainly going to be more costly than adjusting the orc's hit points (changing state on an existing object).</li>
<li>And that's a fairly simple case.  It's likely that changes in the object's state will cause other changes -- for example, the orc might get an attack bonus if their hit points drop below a certain level.  In FP, this would probably result in constructing and returning yet another orc object.  And so on.</li>
<li>Constructing new enemy and/or player objects is going to increase the overhead of memory management. All those discarded objects are probably going to need to be garbage collected; and with all that construction / destruction, you're probably going to get fragmentation in the memory store or heap.</li>
</ol>

<p>In general, composability is a good thing.<br>
But it's one thing to talk about <code>f(g(h(x)))</code> when <code>f</code>, <code>g</code>, and <code>h</code> return numeric values.  When each of those functions in the composition chain can return a large and/or complex object ... this may result in unacceptable performance, even for a single-player game.</p>

<p>Now think about a financial application, where reconstructing a customer might involve re-reading several months' (or years') worth of transaction history.</p>

<hr>

<p>As other answers have said, FP is very good at math-y problems.  If you need to manage mutable state, imperative OOP might be a better choice.  Hopefully this makes the difference a bit more concrete.</p>

CC BY-SA 3.0
2017-08-09T19:22:51.077Z
Welcome to [cseducators.se]! A very in depth answer, addressing many points. Thanks.
ItamarG3
CC BY-SA 3.0
2017-08-10T08:15:23.257Z
There is this "Myth of the Sufficiently Smart Compiler". In theory, a compiler could inline `g` and `h` into `f`, perform an escape analysis to realize that the reference cannot have escaped, and therefore modify the value in place since no observer can realize the modification. Of course, a language without GC would make this much easier (eliding escape analysis partially).
Matthieu M.
CC BY-SA 3.0
2017-08-09T19:21:05.070Z
2017-08-09T19:21:05.070Z
David
<p>Here I will discuss Functional Programming (FP) and Object Oriented Programming (OOP) in a fairly pure form. Actual languages, however often make compromises to allow older forms as well as multi-paradigm programming.</p>
<p>Both FP and OOP rely in the notion of program &quot;State&quot; but do so in different ways. In fact there are really two different things that go by the term &quot;state&quot; and it is useful to distinguish between them. The version most people focus on when they say &quot;state&quot; is the current set of values of variables in a program, whether held in objects or not. This depends on having modifiable &quot;variables&quot; in the program.</p>
<p>Using Pascal notation, x := 2 gives an integer variable a value 2. You set a state. Later, within the same scope, you are allowed to say x := 3 which &quot;changes the state&quot;.</p>
<p>The way most people visualize the above is that the memory of some real or abstract machine has been altered in a specific way. I will refer to this notion of &quot;state&quot; as <em>Explicit State</em>. The Explicit State is the current collection of values of variables.</p>
<p>However, there is a different, independent view of &quot;state&quot; that most programmers are aware of, but don't always focus on in the same way. In this view, the &quot;state of a computation&quot; is represented by the program counter, which represents the current focus of execution in a program. For example now using Java-like syntax:</p>
<pre><code>if(x == 3){
    // a
    ....
} else {
    //b
    ....
}
</code></pre>
<p>At some point in the execution the program counter (PC) may be at point (a) or at point (b), but not both simultaneously, of course. If the PC is at point (a) then the &quot;state of the computation&quot; includes the fact that x is 3. If it is at point (b) then the state is that x is not 3. In this view the state of the computation changes as the program executes (and is dynamic). In the former view the program state is often thought of as static, though that isn't quite correct (since things change). I will refer to this second notion of &quot;state&quot; as <em>Implicit State</em>. It is the current location of the PC and all that implies about what has gone before, no matter how implemented.</p>
<p>Now to the question: What is the fundamental difference between (pure)FP and (pure)OOP?</p>
<ul>
<li>Functional Programming</li>
</ul>
<p>Pure FP relies on implicit state and deemphasizes (or eliminates) explicit state. In Scheme, for example, a <em>let</em> gives a value to an identifier that is valid throughout a scope. It is <em>called</em> a variable in the documentation, but it is really a name given to a constant. Once given a value the name doesn't refer to any other value in that scope, but might have a different value in a different (or larger, or smaller) scope.</p>
<p>One envisions a computation in a pure FP as an expression that has a value. In order to calculate that expression other expressions are evaluated (recursively, so to speak) until some expressions evaluate to themselves (5, and &quot;foo&quot;). The state of the computation is purely implicit, the location of the PC within the chain of recursion. When the chain ends the original expression can yield a value.</p>
<p>There are no &quot;variables&quot; in the C or Pascal sense. Named values (i.e. constants) may be assigned to memory locations or stored on the stack, or in the cloud, or ... It isn't necessarily specified. In a sense, the state is a Stack.</p>
<ul>
<li>Object-Oriented Programming</li>
</ul>
<p>The first OOP was actually Simula (1967), developed in Scandinavia to do simulation programming. Simula was the main inspiration for C++. The first (and maybe only) <em>pure</em> OOP was/is Smalltalk. It became the inspiration for most other modern OOPs; Apple Object Pascal, Java, Python, .... However, most other OOP languages than Smalltalk compromise in a number of ways. To discuss pure OOP more deeply requires an excursion. There are two ways to think about an object in an OOP; its creation and its use.</p>
<ul>
<li>Object Usage in Pure OOP</li>
</ul>
<p>In pure OOP an object exists (somehow) and is best viewed as a &quot;bundle of behavior&quot;. It responds to a set of messages that are valid for its type. The messages may contain parameters. Whether or not it has anything like &quot;state&quot; is immaterial. It &quot;behaves&quot; when sent a message. As part of carrying out its task (as defined by the message and parameters) it may, itself, send messages to other objects. Some messages are functional in nature and return values (objects or primitive values). Some are not. You need non-functional methods to, for example, drive printers and other external devices.</p>
<p>In this view it is not fruitful to think of objects as encapsulating &quot;state&quot;. The state is not material. Only the behavior matters. The implementation of an object <em>might</em> rely on saved state, or it <em>might</em> rely on delegating things to other objects through a chain of messages (again, like recursion to some base case).</p>
<p>Objects <em>when used</em> are bundles of behavior, nothing more.</p>
<ul>
<li>Object Creation in Pure OOP</li>
</ul>
<p>OOP languages, however also provide a mechanism for the creation of objects. There are two main mechanisms for this (Classes and Prototypes), which don't affect the discussion here. I will assume a class-based languages since most (non javascript) programmers are most familiar with classes. In creating a class definition the job of the programmer is to define the behavior of its objects. In Java, that means the visible methods (visibility is a bit complex for this discussion, think non-private for a simplification).</p>
<p>An object of the new class must be able to respond to a given message (with parameters, perhaps). That can be made to happen in different ways. For example, the object might defer the action to another object. But it might also define a (classic) variable, and give it a value. Having given that variable a value, it is free to retrieve it later and (perhaps) modify it. But don't be naive about things. Just because the name of a method is &quot;setDisplay&quot; doesn't necessarily mean that there is some variable (anywhere) that will have its value changed. It is a concept, nothing more. The object will <em>somehow</em> (up to the programmer) retain the value given so that the &quot;state of the computation&quot; can move forward.</p>
<p>So, in this &quot;pure&quot;OOP view, the job of creation of objects is the job of defining the behaviors to which the object can respond. You can think of an object (if you like) as a bundle of state + behavior, but that should only work at the definitional stage, not the usage stage.</p>
<p>Note that in this view, a computation is seen as a collection of independent objects that communicate via message passing. The objects may be normally active (actor model) or not, with the latter being more common. An object is, in the non-actor case, only active when it has been sent a message. It is easy to visualize that a PC comes along with any message allowing the object to execute the method. If the object sends a message itself, the PC is passed along as well, letting the receiver of the message act.</p>
<ul>
<li>Why this OOP view is important.</li>
</ul>
<p>One of the problems of learning to program is the problem of how much information needs to be kept in mind as you proceed. If it was necessary to retain every detail of the program, it would be an impossible task. Therefore we use various abstraction facilities (mental facilities) to reduce the task. I can't remember the state of 4gb of values. I can't even really remember the implicit state of an if-statement if nested more than about 4 levels deep. Therefore I don't write such programs and instead create simple objects with simple behaviors. I also create objects that have any explicit state private - no exceptions. I design objects so that I <em>can</em> effectively think of them as <em>nothing but</em> bundles of behavior, though Java certainly has facilities that let me do otherwise. However, if I break my rules, my program becomes harder to understand, use, and modify.</p>
<ul>
<li>A pure OOP program is a set of simple objects with simple methods. The complexity of the program is in the interactions of objects, not implementations of the objects.</li>
</ul>
<p>Yes, I write a lot of classes. But each is simple to conceptualize and simple to build. Each object is a bundle of behavior, nothing more.</p>

CC BY-SA 3.0
2017-08-09T14:27:54.197Z
Actually, I _don't_ have a preference for FP. In fact the only functional language I was ever any good at was ML. I depend on concrete syntax to help organize my thoughts. My view is truly OOP, just a deeper, purer version than most people have and few OOP languages require. The only really serious software I've built (quite a bit) has been in OO languages. But my experience goes back a long way and I've tried to develop a style that is sustainable. My view isn't unique, of course. Glad I was helpful.
Buffy
CC BY-SA 3.0
2017-08-09T16:46:50.287Z
Well, my "serious" software is also fun. It should be fun. In the above reference, however, serious also meant more than 15K deployments.
Buffy
CC BY-SA 3.0
2017-08-10T21:10:31.093Z
Functional languages often use the term "variable" like mathematics – a name for some value which is constant during its lifetime, but the same name may refer to a different value the next time the algorithm is run. A true constant has the same value each time.
Paŭlo Ebermann
CC BY-SA 4.0
2017-08-09T12:50:05.730Z
2022-10-03T19:51:28.660Z
2022-10-03T19:51:28.660Z
Buffy
<p>I've been trying to learn the differences between Functional Programming and OOP, but I can't seem to find a comparison of the two.</p>

<p>A Google search did not yield any chart or table showing such a comparison.</p>

<p>From the unclear Google search, however, I have come up with this:<br>
OOP keeps actions and data encapsulated in objects, Functional Programming separates the two.</p>

<p>But that doesn't actually give a useful comparison of the usecases for each one.</p>

<p>So, my question is where might I find a thorough comparison between the two, which can explain which should be used for some kinds of tasks\projects? I'm looking for some explanation\comparison of various aspects of these paradigms.</p>

<p>The types of projects or tasks I am referring to are varied, but can be classified into: Computer Management (similar to what userscripts allow in browsers) and Utilities (units conversion, custom shell). </p>

<p>(off site resources are considered an answer, as well as answers giving such a comparison without an off site resource)</p>

CC BY-SA 3.0
2017-08-09T08:59:32.383Z
I think this topic is already reasonably well-covered on other SE sites: I'd start by reading the first few answers in [this post](https://softwareengineering.stackexchange.com/q/9730/45762) and [this post](https://stackoverflow.com/q/24279/646543), as well as recursively reading every linked off-site resource + every related question in the sidebar.
Michael0x2a
CC BY-SA 3.0
2017-08-09T09:14:49.567Z
@Michael0x2a yikes. Well, I better get started.
ItamarG3
CC BY-SA 3.0
2017-08-09T15:20:13.567Z
In FP, functions may be applied to other functions, or to data containing functions, so the worlds of data and functions are not that much separated  (think about a sort() function, with a comparator function as parameter).
Michel Billaud
CC BY-SA 3.0
2017-08-10T17:30:10.253Z
I think it's also important to note how difficult it can be to read and comprehend the benefits of something like functional programming.  For me anyway, it took programming imperatively for a long time to realize the complexity that modified state brings.  Once I realized that was a real problem I had to solve, functional programming was a natural solution and all the material explaining what functional programming was started to make sense.
aaaaaa
CC BY-SA 3.0
2017-08-11T22:02:53.327Z
I also recommend Eric Lippert's excellent answer to [Why hasn't functional programming taken over yet?](https://stackoverflow.com/questions/2835801/why-hasnt-functional-programming-taken-over-yet) from SO.
Jeffrey Bosboom
CC BY-SA 3.0
2017-08-12T14:51:26.027Z
Others here have mentioned the theory behind functional programming. If you want to see the theory behind OOP, see [_A Theory of Objects_](https://www.amazon.com/Theory-Objects-Monographs-Computer-Science/dp/0387947752) by Abadi and Cardelli. (Not cheap, not easy).
Buffy
<self-learning><object-oriented-paradigm><functional-programming>
Learning fundamental differences between functional programming and Object Oriented Programming
# Learning fundamental differences between functional programming and Object Oriented Programming

(Asked by: username_0 on 2017-08-09)

I've been trying to learn the differences between Functional Programming and OOP, but I can't seem to find a comparison of the two.

A Google search did not yield any chart or table showing such a comparison.

From the unclear Google search, however, I have come up with this:  
OOP keeps actions and data encapsulated in objects, Functional Programming separates the two.

But that doesn't actually give a useful comparison of the usecases for each one.

So, my question is where might I find a thorough comparison between the two, which can explain which should be used for some kinds of tasks\projects? I'm looking for some explanation\comparison of various aspects of these paradigms.

The types of projects or tasks I am referring to are varied, but can be classified into: Computer Management (similar to what userscripts allow in browsers) and Utilities (units conversion, custom shell).

(off site resources are considered an answer, as well as answers giving such a comparison without an off site resource)

**Tags:** self-learning, object-oriented-paradigm, functional-programming

> **Comments:**
> **username_1**: I think this topic is already reasonably well-covered on other SE sites: I'd start by reading the first few answers in [this post](https://softwareengineering.stackexchange.com/q/9730/45762) and [this post](https://stackoverflow.com/q/24279/646543), as well as recursively reading every linked off-site resource + every related question in the sidebar.  
> **username_0**: @username_1 yikes. Well, I better get started.  
> **username_2**: In FP, functions may be applied to other functions, or to data containing functions, so the worlds of data and functions are not that much separated  (think about a sort() function, with a comparator function as parameter).  
> **username_3**: I think it's also important to note how difficult it can be to read and comprehend the benefits of something like functional programming.  For me anyway, it took programming imperatively for a long time to realize the complexity that modified state brings.  Once I realized that was a real problem I had to solve, functional programming was a natural solution and all the material explaining what functional programming was started to make sense.  
> **username_4**: I also recommend Eric Lippert's excellent answer to [Why hasn't functional programming taken over yet?](https://stackoverflow.com/questions/2835801/why-hasnt-functional-programming-taken-over-yet) from SO.  
> **username_5**: Others here have mentioned the theory behind functional programming. If you want to see the theory behind OOP, see [_A Theory of Objects_](https://www.amazon.com/Theory-Objects-Monographs-Computer-Science/dp/0387947752) by Abadi and Cardelli. (Not cheap, not easy).  

---

## 10 answers

### Answer by username_9 on 2017-08-09. Score: 59 | Accepted answer

There are beautiful answers to this question already here, and I will not try to reiterate any of the ground that has already been covered. However, something important that I have not seen here so far is that comparing OOP to FP is not actually terribly meaningful. It's a bit like comparing *glass* (the material) to *tables* (the furniture). They each have properties that can be explored, but even if discussions of these properties can help you learn about them, the comparison itself doesn't actually tell you much about either. Glass tables exist, and have the properties of both. Similarly, Scala, Clojure, and Swift are languages that are *both* functional and OO.

A more meaningful comparison for functional programming is imperative programming. The most popular languages in the world right now are all imperative**1**. Imperative languages focus on mutable values and states, and are historically based on **Turing Machines**. Functional languages are all about function calls and immutable constants, and are historically based on Church's **$\lambda$-Calculus**.

The two mathematical systems were developed around the same time in order to solve the same question: *what is fundamentally computable?* The **Church-Turing Thesis**, which was published before electronic computers existed, proved that the two systems were equally powerful, and further hypothesized that they could both compute any computable function, and that any *sufficiently complex system* could embody exactly this same computability power.

A more meaningful comparison for Object-Oriented programming would be... well, *nothing*. The Object-Oriented philosophy, which is about grouping data with functions that govern that data, can be applied to any programming paradigm. Object-Oriented programming is all about the *scope and membership* of functions and data. It doesn't matter if the data is mutable, if the order of operations is defined, how data is stored, whether functions are mutable... if we are creating instances of data that are bundled with their own functions, the we have the kernel of object-oriented programming.

**1** - Only if you discount Excel, which is actually a light functional programming language, and is almost certainly used by *many more people* than any other programming language on earth.

> **Comments:**
> **username_17**: +1, You could compare object oriented to data oriented, though.  
> **username_18**: The opposite of OOP would seem to be maintaining a separation between data and behavior.  (These opposites aren't mutually exclusive, though - I've seen programs that mix imperative *and* functional *and* OOP *and* separation of data and behavior - they just do different things in different places.)  
> **username_19**: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/63722/discussion-on-answer-by-ben-i-learning-fundamental-differences-between-function).  

---

### Answer by username_5 on 2017-08-09. Score: 16

Here I will discuss Functional Programming (FP) and Object Oriented Programming (OOP) in a fairly pure form. Actual languages, however often make compromises to allow older forms as well as multi-paradigm programming.
Both FP and OOP rely in the notion of program "State" but do so in different ways. In fact there are really two different things that go by the term "state" and it is useful to distinguish between them. The version most people focus on when they say "state" is the current set of values of variables in a program, whether held in objects or not. This depends on having modifiable "variables" in the program.
Using Pascal notation, x := 2 gives an integer variable a value 2. You set a state. Later, within the same scope, you are allowed to say x := 3 which "changes the state".
The way most people visualize the above is that the memory of some real or abstract machine has been altered in a specific way. I will refer to this notion of "state" as Explicit State. The Explicit State is the current collection of values of variables.
However, there is a different, independent view of "state" that most programmers are aware of, but don't always focus on in the same way. In this view, the "state of a computation" is represented by the program counter, which represents the current focus of execution in a program. For example now using Java-like syntax:
if(x == 3){
    // a
    ....
} else {
    //b
    ....
}

At some point in the execution the program counter (PC) may be at point (a) or at point (b), but not both simultaneously, of course. If the PC is at point (a) then the "state of the computation" includes the fact that x is 3. If it is at point (b) then the state is that x is not 3. In this view the state of the computation changes as the program executes (and is dynamic). In the former view the program state is often thought of as static, though that isn't quite correct (since things change). I will refer to this second notion of "state" as Implicit State. It is the current location of the PC and all that implies about what has gone before, no matter how implemented.
Now to the question: What is the fundamental difference between (pure)FP and (pure)OOP?

Functional Programming

Pure FP relies on implicit state and deemphasizes (or eliminates) explicit state. In Scheme, for example, a let gives a value to an identifier that is valid throughout a scope. It is called a variable in the documentation, but it is really a name given to a constant. Once given a value the name doesn't refer to any other value in that scope, but might have a different value in a different (or larger, or smaller) scope.
One envisions a computation in a pure FP as an expression that has a value. In order to calculate that expression other expressions are evaluated (recursively, so to speak) until some expressions evaluate to themselves (5, and "foo"). The state of the computation is purely implicit, the location of the PC within the chain of recursion. When the chain ends the original expression can yield a value.
There are no "variables" in the C or Pascal sense. Named values (i.e. constants) may be assigned to memory locations or stored on the stack, or in the cloud, or ... It isn't necessarily specified. In a sense, the state is a Stack.

Object-Oriented Programming

The first OOP was actually Simula (1967), developed in Scandinavia to do simulation programming. Simula was the main inspiration for C++. The first (and maybe only) pure OOP was/is Smalltalk. It became the inspiration for most other modern OOPs; Apple Object Pascal, Java, Python, .... However, most other OOP languages than Smalltalk compromise in a number of ways. To discuss pure OOP more deeply requires an excursion. There are two ways to think about an object in an OOP; its creation and its use.

Object Usage in Pure OOP

In pure OOP an object exists (somehow) and is best viewed as a "bundle of behavior". It responds to a set of messages that are valid for its type. The messages may contain parameters. Whether or not it has anything like "state" is immaterial. It "behaves" when sent a message. As part of carrying out its task (as defined by the message and parameters) it may, itself, send messages to other objects. Some messages are functional in nature and return values (objects or primitive values). Some are not. You need non-functional methods to, for example, drive printers and other external devices.
In this view it is not fruitful to think of objects as encapsulating "state". The state is not material. Only the behavior matters. The implementation of an object might rely on saved state, or it might rely on delegating things to other objects through a chain of messages (again, like recursion to some base case).
Objects when used are bundles of behavior, nothing more.

Object Creation in Pure OOP

OOP languages, however also provide a mechanism for the creation of objects. There are two main mechanisms for this (Classes and Prototypes), which don't affect the discussion here. I will assume a class-based languages since most (non javascript) programmers are most familiar with classes. In creating a class definition the job of the programmer is to define the behavior of its objects. In Java, that means the visible methods (visibility is a bit complex for this discussion, think non-private for a simplification).
An object of the new class must be able to respond to a given message (with parameters, perhaps). That can be made to happen in different ways. For example, the object might defer the action to another object. But it might also define a (classic) variable, and give it a value. Having given that variable a value, it is free to retrieve it later and (perhaps) modify it. But don't be naive about things. Just because the name of a method is "setDisplay" doesn't necessarily mean that there is some variable (anywhere) that will have its value changed. It is a concept, nothing more. The object will somehow (up to the programmer) retain the value given so that the "state of the computation" can move forward.
So, in this "pure"OOP view, the job of creation of objects is the job of defining the behaviors to which the object can respond. You can think of an object (if you like) as a bundle of state + behavior, but that should only work at the definitional stage, not the usage stage.
Note that in this view, a computation is seen as a collection of independent objects that communicate via message passing. The objects may be normally active (actor model) or not, with the latter being more common. An object is, in the non-actor case, only active when it has been sent a message. It is easy to visualize that a PC comes along with any message allowing the object to execute the method. If the object sends a message itself, the PC is passed along as well, letting the receiver of the message act.

Why this OOP view is important.

One of the problems of learning to program is the problem of how much information needs to be kept in mind as you proceed. If it was necessary to retain every detail of the program, it would be an impossible task. Therefore we use various abstraction facilities (mental facilities) to reduce the task. I can't remember the state of 4gb of values. I can't even really remember the implicit state of an if-statement if nested more than about 4 levels deep. Therefore I don't write such programs and instead create simple objects with simple behaviors. I also create objects that have any explicit state private - no exceptions. I design objects so that I can effectively think of them as nothing but bundles of behavior, though Java certainly has facilities that let me do otherwise. However, if I break my rules, my program becomes harder to understand, use, and modify.

A pure OOP program is a set of simple objects with simple methods. The complexity of the program is in the interactions of objects, not implementations of the objects.

Yes, I write a lot of classes. But each is simple to conceptualize and simple to build. Each object is a bundle of behavior, nothing more.

> **Comments:**
> **username_5**: Actually, I _don't_ have a preference for FP. In fact the only functional language I was ever any good at was ML. I depend on concrete syntax to help organize my thoughts. My view is truly OOP, just a deeper, purer version than most people have and few OOP languages require. The only really serious software I've built (quite a bit) has been in OO languages. But my experience goes back a long way and I've tried to develop a style that is sustainable. My view isn't unique, of course. Glad I was helpful.  
> **username_5**: Well, my "serious" software is also fun. It should be fun. In the above reference, however, serious also meant more than 15K deployments.  
> **username_24**: Functional languages often use the term "variable" like mathematics – a name for some value which is constant during its lifetime, but the same name may refer to a different value the next time the algorithm is run. A true constant has the same value each time.  

---

### Answer by username_20 on 2017-08-09. Score: 9

FP and OOP are both tools in the box, none of them is better or worse. The same way you would not ask whether to use a hammer or a screwdriver to put in a nail, you should not ask whether to use FP or OOP. 
The question should be: what is the best way to solve your problem at hand?
OOP excels when you need to describe abstract objects with code (hence the name). Describing the abilities and features of a car is something FP is not made for, so choosing FP for this situation would be painfully complicated.
Vice versa FP excels when algorithms can be written as mathematical functions in the mindset of f(x) -> y (more complex functions are also very much possible). Using OOP to describe the result of square(x) is possible but pointlessly complicated.
In modern programming FP is usually used when volumes of data need to be transformed. If you need to map from Z to Y by using the transformation function f, then you can very simply write that in code using FP, i.E. in Java like this:
// equivalent of Yn = f(Zn)
List myYs = myZs.stream()      // for each z in Z
  .map(MyClass::f)                // transform y = f(z)
  .collect(Collectors.toList());  // and store y in a list

Doing the same in OOP would look something like this:
class Z {
  private int myValue;

  public int getValue() {
    return this.myValue;
  }
}

class Y extends Z {
  static Y convertFromZ(final Z z) {
    // ...
  }

  @Override
  public int getValue() {
    return convertFromZ(super.getValue());
  }
}

List myYs = (List) myZs;  // <-- really dirty hack

This makes it hopefully obvious why such a comparison chart does not exist: because those two are entirely different concepts.

> **Comments:**
> **username_0**: Welcome to [cseducators.se]! that's a very useful overview and explanation. Thanks!  
> **username_21**: I would ask whether to use a nail or a screw, e.g.: http://www.popularmechanics.com/home/tools/how-to/a18606/nails-vs-screws-which-one-is-stronger/ .  OO vs FP is different in that it's possible (reasonable) to do both, e.g. making `x.square()` return a new object or writing a method `expr.calculated_type()` in a compiler.  

---

### Answer by username_22 on 2017-08-09. Score: 9

I wouldn’t expect to find a comparison table because OOP and FP are not mutually exclusive concepts.

OOP is about encapsulating data in objects behind interfaces and using inheritance to build objects in re-usable pieces.

FP, however, is about not changing states or having side-effects.

You can have an OOP program with immutable objects. (You can *clone* an object, but you can’t change the state of an existing object.) You can have an OOP program where the methods have no side-effects.

You can have a FP program that encapsulates its data in objects behind interfaces and uses inheritance.


---

### Answer by username_23 on 2017-08-09. Score: 9

There are already several good answers, but I'd like to add the following.

Functional code is (at least in theory) more easily parallellized. This is important because we've about hit the limit of how fast we can run integrated circuits. (I know that's an oversimplification; I'm trying to keep it simple for the OP's audience's sake.)  
So, while you can't make the individual cores on your CPU run much faster, you *can* add cores to the CPU.

Now let's think about a single large program. Multiple cores will only speed up such a progrm if it can be broken up into independent "chunks" that can be parcelled out to individual cores. And let's be clear about what "independent" means: no one chunk should have side effects that can affect any other chunk (and probably chunks should not depend on the output of other chunks).

This is an area where functional programming excels. By contrast, trying to ensure object consistency across multiple threads or processes can be a nightmare. Which is one reason there's a great deal of current interest in FP.

The downside is ... as Jared points out, in a game, in the FP paradigm, you'd likely maintain statelessness by having the "attack" routine return a whole new copy of the orc (or whatever enemy) under attack. But:

1. Reconstructing the entire orc is probably a non-trivial operation -- it's almost certainly going to be more costly than adjusting the orc's hit points (changing state on an existing object).
2. And that's a fairly simple case. It's likely that changes in the object's state will cause other changes -- for example, the orc might get an attack bonus if their hit points drop below a certain level. In FP, this would probably result in constructing and returning yet another orc object. And so on.
3. Constructing new enemy and/or player objects is going to increase the overhead of memory management. All those discarded objects are probably going to need to be garbage collected; and with all that construction / destruction, you're probably going to get fragmentation in the memory store or heap.

In general, composability is a good thing.  
But it's one thing to talk about `f(g(h(x)))` when `f`, `g`, and `h` return numeric values. When each of those functions in the composition chain can return a large and/or complex object ... this may result in unacceptable performance, even for a single-player game.

Now think about a financial application, where reconstructing a customer might involve re-reading several months' (or years') worth of transaction history.

---

As other answers have said, FP is very good at math-y problems. If you need to manage mutable state, imperative OOP might be a better choice. Hopefully this makes the difference a bit more concrete.

> **Comments:**
> **username_0**: Welcome to [cseducators.se]! A very in depth answer, addressing many points. Thanks.  
> **username_14**: There is this "Myth of the Sufficiently Smart Compiler". In theory, a compiler could inline `g` and `h` into `f`, perform an escape analysis to realize that the reference cannot have escaped, and therefore modify the value in place since no observer can realize the modification. Of course, a language without GC would make this much easier (eliding escape analysis partially).  

---

### Answer by username_6 on 2017-08-09. Score: 7

This is a very broad question, so I'm going to point you to a couple places and then give a really short explanation.

* Wikipedia on paradigms: <https://en.wikipedia.org/wiki/Programming_paradigm>
  + I'm linking to the main article, but linked at the bottom you should definitely check out the "Comparison" article as well as the specific sections and links to functional and OOP stuff.
* this SO post is pretty decent, <https://stackoverflow.com/questions/552336/oop-vs-functional-programming-vs-procedural>

---

I think it's important to have the right mindset about paradigms: At the end of the day, they're a tool to help you organize a thought process around code. They all let you accomplish the same tasks.

In general, nearly every language or environment today is 'multi-paradigm'. Even Java (which is famously OOP because everything is required to be in a class) is written in a style that blends imperative and procedural paradigms with OOP. More recently, Java includes more and more elements that are in the functional style.

When in comes to functional vs OOP, there's one big thing that comes to mind.

Being "stateless" or having "state"

State means that you have some stored properties or information, like the name of a sprite, or a display where you output information.
In a functional world, especially one that tries to be "pure", you're mostly going to be dealing with composing (or chaining) functions together. The goal is to have a function, say `compute_something(an_object)` that needs only the information passed into it (arguments) and nothing else - i.e. It has no "state". It will then return a new value, and not modify or mutate it's input.
In the OOP world, it's common to think of an object having state, it's information about itself and how it interacts with the world. You might do something like `object.compute_something()`, where `compute_something` is a property (a function) tied to that object, and by calling it, you modify some property of that object.

One common example of this is sorting a list. In a functional paradigm, you'd probably do `sorted_list = sort(some_list)`. While in an OOP paradigm, you'd likely do `some_list.sort()` and the next time you use `some_list` it will be sorted.

Form this there are sometimes other differences, like how difference languages treat "types" of data, but things can get muddied quickly.

---

To answer your original question about projects: It really is hard to say. You could conceptualize a Unit conversion app as having a bunch of objects (like one for each type of measurement system), or since it's "mathy-" you could just as easily conceptualize as a simple function with a lookup table for various conversion rates. In reality the paradigm will depend on the environment that you're working with as much as it will depend on the theoretic structure of code.

> **Comments:**
> **username_0**: Interesting. I had not thought of some of the things you pointed out. Thanks  
> **username_7**: “While in an OOP paradigm, you'd likely do some_list.sort() and the next time you use some_list it will be sorted.” No. With an **imperative** paradigm, you'd do `sort(some_list)` (procedural) or `some_list.sort()` (OO) to change `some_list`. OO vs procedural is orthogonal to imperative vs functional. In functional OOP, you'd do `let sorted_list = some_list.sort()`.  

---

### Answer by username_8 on 2017-08-09. Score: 5

As I read your post, I see your question as simply this:

> where might I find a thorough comparison between the two [OOP and FP], which can
> explain which should be used for some kinds of tasks\projects?

The best explanation I have seen is in the context of the Programming Languages MOOCs offered through Coursera modeled after [this course at UW](http://courses.cs.washington.edu/courses/cse341/17sp/).

The class works through, in order, a statically-typed functional language (ML), a dynamically-typed functional language (Racket), and a dynamically-typed object-oriented language (Ruby). Since this is an upper-division course and students presumably are somewhat familiar with it, Java is thrown in for comparisons when relevant as a statically-typed objected-oriented language.

**If you want to find a thorough comparison, build projects with each approach, spending time to learn the relevant nuances of FP and OOP along the way.** There is no chart or tutorial that can substitute for this work; it simply takes time and practice. Based on my experience, the work of this course will not disappoint. There are short mini-lecture videos, excellent reading notes, and challenging homework assignments all available for free.

At the end of the course, the professor does an excellent job breaking down OOP v. functional decomposition. By the time you reach the end, you will have a clear picture as to how these approaches differ, where their relative strengths and weaknesses like, and when/how to apply each paradigm to a particular problem.

> **Comments:**
> **username_9**: I disagree with you that you will learn about *"how these approaches differ"* - they don't differ in any meaningful way.  They are orthogonal concepts from the start. It's like saying that you will learn how *tennis* differs from *clay* (of which the court is made), or how *paintings* differ from *paper*.  
> **username_8**: @BenI. I'm not enough of a programming languages expert to speak with my own authority on such a matter, but I have a feeling the professor sees things differently. The end of the course dives in to how each approach takes fundamentally opposite approaches to program decomposition. From the lecture notes: "We show that the two approaches [OOP and FP] largely lay out the same ideas in exactly opposite ways." https://courses.cs.washington.edu/courses/cse341/17sp/unit8notes.pdf  
> **username_9**: In that case, my disagreement is with the professor. Perhaps he overstated his case? The sentence that you have quoted would seem to be disproven by the existence of the many functional, object-oriented languages.  
> **username_9**: @nocomprende Your statement is beautiful, but I suspect it is ultimately more poetic than it is meaningful. Godel is talking about the limits of *provability*, which is simply unrelated to the notion of whether various engineering philosophies can play nicely with one another.  

---

### Answer by username_10 on 2017-08-09. Score: 5

It is difficult to put this into a form that inexperienced undergraduate students will appreciate, but well...

> "It is commonly the case with technologies that you can get the best insight about how they work by watching them fail" - Neal Stephenson, *In the Beginning was
> the Command Line*

Since OOP is the 500lb gorilla of the programming world and FP the relative upstart this comparison might be a bit skewed for want of data points. However two prominent failure cases come to mind.

## 1. Data Interchange

The Sun God Microsystems bestowed upon the Paladin Knights of Programmingdom his Commandments etched into tablets of purest silicon for posterity and from whence His disciples founded the Church of Java. Any who were so foolish as to claim that these commandments from on high were a Pact with the Devils of Performance and Popular Sintax bastardizing the pristine purity of Smalltalk were denounced as heretics. And the proselytizers spread their faith unto the remotest corners of the kingdom.

So yeah, people started using OOP for everything. But there was (at least) one arena where this failed entirely: IPC. Exchanging data across the boundary of threads/machines/networks/languages was an issue. Exactly how much of an issue can be inferred from enumerating some of the (many) attempts at solving it in an OO fashion that litter the scrapheap of history: CORBA, RMI, WSDL, DCOM... and also from the extreme proliferation of using plain ol data generally in the form of XML (as opposed to using XML-RPC).

So now people still do this, but generally we use transport mechanisms that are *stateless* (like HTTP) and over them we send language-agnostic data (sexprs, XML, JSON). So in structuring intercommunicating *systems* FP won because dealing with state is hard enough on its own but becomes an order of magnitude harder when you add threads, then another order of magnitude (or two) harder when you add inter-machine communcations and another order of magnitude (or more!) harder still when you have many-to-many communications with needs for eventual consistency or accurate chronological ordering of events. In fact, just thinking about it enough to write that last bit raised my blood pressure to dangerous levels.

Which is not to say that people don't use OOP in that space at all anymore, but it's not super common and the search to find the Great-OOP-Protocol-that-Makes-it-EZ is a pursuit more easily compared to [cold fusion](https://en.wikipedia.org/wiki/Cold_fusion) or the [Lost City of El Dorado](https://en.wikipedia.org/wiki/El_Dorado) (no VC funding for you!) than trying to create the next megahit social networking app (\$\$purr\$\$).

## 2. Games Programming.

Programming games in FP is [certainly possible](http://prog21.dadgum.com/23.html), but not necessarily recommended. And this goes beyond lack of libraries and middleware or the need to squeeze as much out of the hardware as possible: when my level 6 Half-Elf Berserker bashes an orc with her Hammer of Doom I expect that orc to be the same orc minus 3D6 hp not a new orc with a different hp value than the old one. The problem is that games deal generally with two different entities: *things* and *rules* about the interaction of those things *as they change over time*. No one wants to go all War Games and watch a supercomputer [play itself at tic-tac-toe](https://www.youtube.com/watch?v=F7qOV8xonfY) until it learns the futility of nuclear war. OOP [sucks at modelling rules](https://ericlippert.com/2015/04/27/wizards-and-warriors-part-one/) (which FP excels at), but OOP is *great* for modelling how reified things *change over time*.

Anyways, as I said at the beginning I'm not exactly sure how I'd go about making all of this accessible to CS undergrads (based on my memory of what I and my peers were like when I was one). But I think looking at two high profile failures is a good place to start.

Bottom line, as the other answers have said they are extremely different mental models. Anytime you try to use one that doesn't easily map to the problem domain you're going to have issues. So illustrating some of those domains with how one or the other is a more natural fit (and my examples above of shoving square pegs into round holes) and why might be the best way to approach the topic.

> **Comments:**
> **username_9**: Your history is backwards. Object Oriented programming is the newbie here. FP predates the earliest proto-OO language by a decade. LISP, a functional language based on Church's Lambda Calculus, was the second high-level programming language ever created. It came out just 2-3 months after FORTRAN (the oldest high level programming language that exists).  
> **username_10**: @BenI. I'm aware of the chronology. But in terms of mindshare in the lifetimes of undergraduate students (last ~20yrs) OOP has been utterly dominant. As programming and computer science are rapidly growing, a decent subset (majority?) of persons in the craft came of age in the Javassic Era and are just now being exposed to what LISP and Erlang (and ML and Haskell) have been doing for decades.  
> **username_11**: Regarding your games programming argument: [John Carmack taught his son game programming in Racket](https://twitter.com/id_aa_carmack/status/635839636754038784?lang=en), a LISP dialect.  
> **username_10**: @nocomprende inexact metaphors are always stickier than exact but dry technical discourse :D  
> **username_12**: I don't quite understand what you are getting at with the rant (is it a rant?) about Java.  OOP was around for quite a while before Java, and I don't recall any controversy over whether Java's flavor of OOP was good when compared to Smalltalk.  In any case, Java was more a take on C++ than it was on Smalltalk.  There _was_ serious controversy over C++, but the controversy I remember came from C programmers.  Still does come from C programmers, now that I think of it.  
> **username_10**: @WayneConrad what I'm getting at with my not-rant is that Java was a juggernaut the left it's mark on almost every corner of Programmingland. Many people (not the least of which were Sun's marketing department) hailed it as the One True Language to Replace All Others. Except that it wasn't. The fact that it wasn't quite low-level enough to displace C in some domains and not quite high level enough to replace scripting languages in others doesn't make Java good or bad. In fact, the social-phenomenon aspect makes it rather hard to assess Java simply on its own merits.  
> **username_10**: ...con't so you can't just talk about OOP without talking about Java which not only popularized many OOP concepts but made them *mandatory* knowledge for working programmers. I may not like it, but denying the reality would be foolish in the extreme. Simula didn't do that, smalltalk didn't do that, python didn't do that. Neither did C++ as you point out: people could and did just keep writing C if they wanted to. Java did that. Or more precisely, Sun's brilliant and insanely expensive marketing campaign did that.  

---

### Answer by username_13 on 2017-08-09. Score: 4

Truth be told you will never truly understand the difference until you actually learn and use both a functional and an object oriented language. I say that as someone who has learnt both object-oriented languages (C#, C++, Java) and functional languages (Haskell).
I will however attempt to explain the crux of it.

My answer will be looking mostly at functional programming from an object-oriented point of view, as the features of object oriented programming are already very heavily documented due to its popularity whereas the features of functional programming are much more scarcely documented.

---

Firstly imagine a computer language as a tool (or a collection of tools).
Every tool in the world has a particular purpose or a set of tasks that it's good for, and the same is true of languages.

**Functional languages** tend to work better for problems that involve data-processing and deterministic processes. As such they are liked by scientists and mathematicians who can think in terms of pure data and algorithms.

**Object oriented languages** are better for modelling complex interacting systems. They are preferred by businesses because of their ability to mediate complex tasks and by game developers because of their usefulness in modelling the world.

They can of course be used for other things, but these are typically what the approaches are centred around.

---

At the language level the crux of the matter that sets functional languages apart are these factors:

* They shun local state (with caveats).
* By extension they forbid functions from having side-effects (functional 'purity').
* Implicit type inference
* The dependence on 'lists'
* The use of sum types
* The use of type classes (or 'contracts')
* Implicit currying

(Note that these are not all completely necessary for something to be considered a functional language, but they are features that are commonly associated with functional languages because they can be found in a wide variety of functional languages, particularly the most popular ones.)

**State:**

In a functional language, values are created and they do not change - instead the old value is destroyed and a new value is created. At face value this seems a bit crazy, but in reality this abolition of state (with caveats) is only at the language-level, the compiler translates the source code into machine code that still has a concept of state, which somewhat breaks the illusion and makes this notion a bit less shocking.

The caveats I mentioned are that there are ways to emulate state in one way or another. One way of doing this is by maintaining the state as a function variable and another way is by using a construct called the 'State monad'.

**Purity:**

Equally, although all functions must be 'pure' (i.e. must not have side effects), there are various monads that allow there to still be side effects without breaking the laws of the language. Monads are how any kind of IO (file IO or terminal IO) is made possible. Essentially, the behaviour of the program is bound to the monad through functions that act a a means of sequencing - the monad then represents a list of actions that describe the translation and processing of the data.

**Type inference:**

(This is not found in all functional languages and may sometimes be found in certain object-oriented languages such as C# and C++.)

It is where the compiler is able to evaluate the type of an expression by looking at the types of the values and functions in the expression and deducing what the valid results could be. If there is only one unambiguous match, the compiler is able to infer the type, making many definitions as simple as the values and functions themselves - no explicit typing involved. In other cases, there is ambiguity and some type notation must be used to disabiguate the result.

**Lists:**

Furthermore, the core data type of functional languages is a kind of singly-linked list often referred to simply as a 'list'. This takes the role of the basic collection datatype and is used how arrays and dynamic arrays are used in many object-oriented languages.

Another significant difference is the language-level support for sum types. Sum types are like objects with different constructors, and work *sort of* like inheritance in object oriented languages. That is, the type itself can be an abstract concept (e.g. a tree) and the constructors for it can represent different values of that concept (e.g. and empty tree, a leaf node and a branch node). It is because of this that tree data types are very easily represented in functional languages, and as such they are well-liked for solving mathematical tree-related problems and for implementing parsers and/or compilers.

**Type Classes (or 'contracts'):**

Type classes are similar to interfaces in object-oriented programming but have the distinction that they are not implemented at the time the datatype they are applied to is defined, they are implemented after the type has been defined. This means that they can be applied after the fact to datatypes that one does not 'own'.

Type classes are defined simply as a 'contract' that list a series of functions and/or values for which the obeying datatype must have an implementation. In effect the 'contract' states "any datatype said to implement this type class must provide an implementation for these functions".

For example there could be a datatype `addable a` (Where `a` is a type variable - a symbol standing in for an as yet undeclared type) that specifies a function called `add` with the signature 'a -> a -> a' (a function accepting two arguments of the type represented by `a` and returing a value of the type represented by `a`). This loose definition means the `addable` type class can be implemented by many different data types, including `Int`, `Float` and any user-defined arithmetic type.

**Currying:**

(Note that not all functional languages support this, but it is much more commonly found in functional languages than in object oriented ones.)

Currying is a technique named after Haskell Curry (the same person for whom the language Haskell is named).
Currying means that a function is only bound to one argument and then returns either a result or another function accepting an argument. In functional languages, all functions are implicitly curried, which means that no function actually accepts more than one argument. This in turn means that when you write a statement like `add 3 5`, what actually happens is that the `3` gets bound to the `add` function, which then returns a function accepting a number, to which the `5` gets bound, and only then does that return a result.

This probably seems insane to someone not used to the idea, but it actually makes a lot of things much easier. For example there is typically a function called `map` which takes a function and applies that function over the contents of a list (much like a loop could do in imperative languages), and the ability to curry functions makes the definition of a the function passed to `map` very simple. If, for example, you wanted to add 5 to a list in Haskell, you could simply write `map (+5) list` - the `(+5)` takes the function `+`, binds it to the value `5` and returns a function taking a number and returning the result of that number `+ 5`.

> **Comments:**
> **username_14**: I am afraid this answer conflates Functional Programming and Haskell. At the very least Type Inference, Type Classes and Currying are NOT a hallmark of FP.  
> **username_13**: @MatthieuM. Could you give some examples of functional languages that do not have these features? Also I was under the impression that the majority of functional languages apply the principles of typed lambda calculus and use a hindley-milner type inference system.  
> **username_14**: Lisp? *(Not sure if it has currying)*  
> **username_13**: @MatthieuM. Ok, I checked and Lisp does indeed not have currying, so I will mark that as a 'sometimes' feature (because it's still more prominent in functional languages than object oriented ones). That doesn't rule out type classes or type inference though. I suspect it's possible type classes are not considered a 'core' feature of functional languages, but I'm pretty sure hindley-milner type inference is because of the relation to typed lambda calculus which is partly what sparked the idea of functional languages in the first place.  
> **username_14**: Lisp is dynamically typed, so no type inference is necessary (or meaningful). Possibilities for making it statically typed are [discussed here](https://stackoverflow.com/questions/3323549/is-a-statically-typed-full-lisp-variant-possible).  
> **username_13**: @nocomprende I just about understood the horse grooming joke thanks to google, but I don't understand the first sentence. No comprende, no comprende.  
> **username_13**: @MatthieuM. I shall mark that as also a 'sometimes' feature, but I believe it's a somewhat popular one that's typically considered to be a feature expected more from functional languages. Or at least [C2 seems to think so](http://wiki.c2.com/?TypeInference). I suspect this is due to the great influence of ML upon other functional languages.  
> **username_13**: @nocomprende I am aware of that saying and its application to computer languages. It's often applied to patterns too. (The bit I got hung up on was the word 'tale', which as far as I know is a synonym for 'story', which doesn't really fit the sentence.) Technically humans are animals. At any rate, this seems like an esoteric, slightly poetic tangent rather than a comment about the answer.  
> **username_13**: @nocomprende "I was just putting in a warning that we often need to take a step back from debates and consider carefully the basis for the whole question. " - _that_ is a fair point. What you had to say was valid, I think your earlier comments were just a bit too crypic at what they were getting at. (Either that or they made perfect sense and I'm just tired.) It's up to you whether you delete them or not, they might be considered 'too chatty' they might not be - I can't really say either way.  
> **username_7**: Currying is inherently possible in any functional language, but whether it's used has little relation with the design of the language. For example Standard ML and Ocaml have a very similar core, but SML favors tuples as function arguments while Ocaml favors currying. (“Favors” means that this is what the standard library uses and the compiler optimizes this case better.)  
> **username_7**: “In a functional language, values are created and they do not change”. In a *pure* functional language. For example, Haskell does not allow values to change (or rather, it requires going through a monad); ML discourages mutable values; Lisp tends to use them a lot.  
> **username_7**: Type inference is only very loosely connected to functional languages, in that the most advanced type systems tend to be implemented on functional languages. Lisp is statically untyped (singly typed if you want to get technical). Many imperative languages are statically typed.  
> **username_13**: @Gilles "Note that these are not all completely necessary for something to be considered a functional language, but they are features that are commonly associated with functional languages because they can be found in a wide variety of functional languages, particularly the most popular ones."  

---

### Answer by username_15 on 2017-08-09. Score: 3

Functional programming is all the rage nowadays. It relies on the illusion that stateless objects and immutable data structures will keep the bugs out. Which is of course nothing but a self-fulfilled prophecy.

Statelessness and immutability are the current Holy Grail and Golden Fleece, mostly because they allows to write junk code faster (a function will always return the same result regardless of the current state of the system, so once it's debugged we're pretty much safe, right?) and we don't know any better way of using these new shining CPUs (functional programming requires a lot more resources than plain old procedural / object oriented approaches - just look at the exponential growth of C++ compile time!).

Functional programming is easier and faster to write. It encourages to concentrate on generic and simple building blocks and follow a bottom-up path.  
On the other hand, it tends to become verbose and unmaintenable fast, what with the layers upon layers of progressively complexified functions you have to write.

With OOP you need at least some top-down approach. A general sketch of your final architecture before you can even start coding. After a couple decades of "extreme" and "agile" programming, the dreams of an easy way out of this initial planning are slowly starting to recede (after having cost an unknown but probably sizeable fraction of the world's GDP in failed projects and botched software). Now, with the shiny GAFAs as role models, functional programming is taking over as the new magical paradigm.

> **Comments:**
> **username_10**: This is full of unsubstantiated opinions and reads more like a rant than an answer. Hype is orthogonal to utility: things can be anywhere in the matrix of sexy/boring and useful/superfluous.  
> **username_13**: I wouldn't say it's all the rage. The only popular 'functional' language I can think of is Rust, and that's more than just plain 'functional', it has OO characterists too - it's more of a hybrid. All the older functional languages are preferred by mathematicians and scientists (or people who like maths and science). Granted many OO languages have adopted pseudo-functional features such as lambda expressions, that doesn't necissarily make them interested in the functional paradigm, rather the implementors have seen a feature they liked and found a use for and adapted it to suit their needs.  
> **username_15**: @username_13 indeed, that's what I call whims of fashion. Templates in C++, stateless and immutable structures all over the web, JavaScript and Python being used as poor man's FP... Immutability and statelessness can be very appealing when dealing with concurrent processes (multithreading that has become mandatory since we started hitting the speed limit of a single CPU, or networking, after 30 years of calamitous efforts to synchronize data brokers), but still they are no silver bullets: costly, hard to read, relying on increasingly complex (and unreliable) tools to reach OOP performances.  
> **username_13**: @kuroineko I wouldn't knock templates because they can be incredibly useful and time-saving *in the right hands* (emphasis important), the ability to write them is certainly more useful for library writers than regular programmers though. I can understand the want for statelesness (it's more about the web's core principle of robustness), but I agree with JavaScript and Python creeping into territory they are unfamiliar with (functionalism).  
> **username_16**: @username_13 Even non-library writers can use templates for creating flexible data structures of their own. Getting deep into template metaprogramming is more something that would be relegated to library or framework code, admittedly, but the ability to delay type/etc. selection to the time of usage is incredibly useful for any programmer writing significantly complex C++ programs.  
> **username_13**: @username_16 They can do if the problem they are solving is well suited to generics (such as writing datastructures or arithmetic types), but those cases occur less frequently than the standard case for most programmers. Plus there's the same danger with templates as there is with programming patterns, and that's the "this is cool, let's make _everything_ a template" mentality. The danger doesn't come from the templates themselves, it comes from them being considered a cool thing to know - it attracts people who will learn _how_ to use them but not _when_ to use them.  

---

