Ask Slashdot: Do You Like Functional Programming? (slashdot.org)
An anonymous reader writes:
Functional programming seems to be all the rage these days. Efforts are being made to highlight its use in Java, JavaScript, C# and elsewhere. Lots of claims are being made about it's virtues that seem relatively easy to prove or disprove such as "Its use will reduce your debugging time." Or "It will clarify your code." My co-workers are resorting to arm-wrestling matches over this style choice. Half of my co-workers have drunk the Kool-Aid and are evangelizing its benefits. The other half are unconvinced of its virtues over Object Oriented Design patterns, etc.
What is your take on functional programming and related technologies (i.e. lambdas and streams)? Is it our salvation? Is it merely another useful design pattern? Or is it a technological dead-end?
Python creator Guido van Rossum has said most programmers aren't used to functional languages, and when he answered Slashdot reader questions in 2013 said the only functional language he knew much about was Haskell, and "any language less popular than Haskell surely has very little practical value." He even added "I also don't think that the current crop of functional languages is ready for mainstream."
Leave your own opinions in the comments. Do you like functional programming?
What is your take on functional programming and related technologies (i.e. lambdas and streams)? Is it our salvation? Is it merely another useful design pattern? Or is it a technological dead-end?
Python creator Guido van Rossum has said most programmers aren't used to functional languages, and when he answered Slashdot reader questions in 2013 said the only functional language he knew much about was Haskell, and "any language less popular than Haskell surely has very little practical value." He even added "I also don't think that the current crop of functional languages is ready for mainstream."
Leave your own opinions in the comments. Do you like functional programming?
but I'm skeptical about functional as the hammer for every nail. Generics and lambda expressions in C++ can make some niche problems disappear entirely by making the compiler do all the work for you, Scheme and Lisp and the like are useful for some very narrow and very academic use cases. As the go-to tool in the tool box? Not so much.
seem to be the prevalent choice on the web these days.
slashdot: A failed experiment.
A properly placed apostrophe has its virtues as well. it's means it is.
It's amazing that people that can learn dozens of languages all more complex than the previous can't seem to grasp the humble apostrophe.
I like functional composition, it certainly has its uses (at least as middleware). I disagree with the notion that it makes code more readable though, in general. It only makes code more readable if you're familiar with it (functional programming).
The heat from below can burn your eyes out
I prefer to use functional programming where it makes sense (most of the time). One reason I like Scala is that it's not pure. You can always write a for loop if you need to. Haskell, is a bit less forgiving.
Use only that which works, and take it from any place you can find it.
I don't get what you mean by "like".
Procedures are procedures, period.
Sometimes it's helpful to have some procedure (or subroutine) store some value in some location before popping the stack.
What I really don't get in this write-up is the insinuation that a focus on (purely) functional programming is a "recent trend". That implies that the majority of today's coders have no fucking idea how coding has progressed through the last few decades (which I've been there to see firsthand).
That's the only interesting thing about this article.
"Stratigraphically the origin of agriculture and thermonuclear destruction will appear essentially simultaneous" -- Lee
But it seems that I will.
Around ten years ago, I started writing a column for a magazine. My first article was precisely a way to use functional programming for "real" code, using a multi-paradigm language (Ruby).
I didn't jump on the Functional bandwagon first time I saw it; it took me around ten years to understand and embrace what it can do. So we are talking about 20 years of hype. At least.
I am far from proficiently thinking functionally, although I have used it for many interesting things. It is a cool, and very different, way to work. It can make many things faster and simpler, but if you completely bite the bullet and make it your dominant paradigm, it will kill your productivity (with many other things that are not best served by that paradigm.
It has a clear spot under your programmer belt. But it should not be The Only Way to approach a program - unless you are Truly One with the Tao.
While I wouldn't want to program in a pure functional, no side effect language, a good mix of differing paradigms seems to me to be the way to go. Java and .NET went overboard on the OOP, and it leads to these poor abstractions in many cases (I.e. AbstractFooProcessor), which are much better approached with some FPd
Pure functional code is super easy to reason about, though, especially asynchronous code. OOP has its role, but oftentimes you find yourself on loose footing, with its focus on always changing state. This can be addressed with good practices, which leads you down class hiearchy hell. Throwing some FP in the mix gives you (mostly) the best of both worlds.
Functional programming languages like Haskell, ML, and Gallina can be very beautiful. The problem is that they have a steep learning curve that has less to do with the syntax of the language and more to do with the semantics. If one is well versed in category theory or has spent a significant amount of time working with functor spaces, monoids, and monads, then it's much easier to understand a non-trivial application written in Haskell than the equivalent object hierarchy in an object-oriented language. The up-front cost is greater in terms of study and learning the semantics, but the end result is significantly more powerful.
I love functional programming. I went from C++ to Haskell and C as my go-to languages for personal projects. However, in my professional work, I tend to factor long-term language popularity into my decisions. So, I'm more inclined to use languages like Java, C#, Go, Python, and Ruby when I'm paid to write software. I have to consider the total cost of ownership in my professional work, and part of that cost is finding people to maintain it years from now.
I think that FP has an elegance that makes it a worthy model, and I hope that some day, FP becomes more popular than OOP. But, I'm old enough to understand that technical superiority rarely wins out to popularity. Popularity matters. This sort of calculus is one of the reasons why FP has not gained much traction despite all of the buzz.
The right question would be "Do you understand functional programming?". And when you see about 99% of all "coders" having no clue, then you could ask the rest why they invested the time.
Most ACs are not even worth the keystrokes to insult them. Be generically insulted by this and ignored otherwise.
yes,
OK a bit more detail, there are advantage to not having state, or at least making the system deal with it it lead to some really elegant code.
Just like most languages it has it limits, mainly input and output.
I have used haskell and I think it has some really good concepts but is plagued by people using being to terse and cryptic, 1 character names for types are not good yes you can work out what it is doing but you shouldn't have to, and the use of random definable operator like '' makes it unreadable without a reference manual for beginners. A part of good code is being clear, being cleaver isn't usually as important as being understandable. At least the uses I have seen generally been quite cryptic.
If the haskel community want haskel to popular they should make an better effort to make it more understandable.
Wow. Really?
Functional programming.
1. Prefer non-mutable data. No more action at a distance bugs. Hand off a reference to your data structure and don't have to care. Replay any data transform at any point as a unique structure.
2. Prefer a defined and well known API often involving transforms that take a function as an argument to provide the predicate (e.g., filter), transform (e.g., map), aggregation (e.g., foldLeft/Right), or whatever building block.
3. Prefer data structures that you can reason about based on a well-known set of patterns. (Best quote ever: "You say `patterns' and everyone is warm and fuzzy. You say `monad' and every loses their f-ing minds.)
Given (2) in a language you'll often see in a language that functions are first-class data.
Functional programming is just (a set of) best-practices. It's scary when the big words are new. Once you use it a bit you'll wonder why when you say, "use a flatMap", folks freak out because all you've said is, "You are transforming the elements of some container into values that are themselves an instance of the same container but you want to flatten everything back from nested containers. [E.g., Container is C with element type A; thus C[A]. You've run a transform that will create C[C[A]] but want to end up with C[A] at the end]." Now you could say that second part but that's a lot of words. Because of points (2) and (3) above we just say, "use a flatMap" (or however you spell `bind` in your language of choice).
Nothing to see here. Please move along. (And yes. I like functional programming. A lot.)
Not sure whether that was an intended pun or not, but I'm using it...
I got my master's degree with this guy, and I had to take a Haskell course, or seminar, every semester. I was, and still am, pretty terrible at Haskell.
However, what I attempted to learn helped my Python out a lot. Map and filter are two of my favorites, and the other functional paradigms are occasionally useful to me as an actually working, productive, programmer. I'm happy I was exposed to those concepts, since they tend to come in handy. Yes, everything is Turing complete, and you can accomplish the same things without functional programming, or without high level language, or without computers, but that doesn't mean they are all equally useful to solving the problem at hand.
I recommend everyone become familiar with functional concepts in some way, if only to make them more well rounded. I don't advocate writing your next web application in Haskell though...
I have a usage pattern where I end up pairing them with enums and it simplifies so many things (e.g. You practically never need a switch statement ever again).
Care to share the pattern (or a reference)? I googled a bit, but there didn't seem to be one stand-out pattern and I'm quite curious (if you have the time)
Thanks.
It's a very useful way of thinking about certain problems and it is often simpler that a lot of pattern heavy code. Take something like a template method. With functional programming just provide the functions to the method or instance. It accomplishes the same thing without an explosion of subclasses.
There's a lot of other classic OO patterns that aren't needed or just done a lot more cleanly with higher order functions and other functional programming paradigms. It's also unfortunate that people assume functional programming is embodied in one language. Haskell is indeed a functional programming language (a highly opinionated one), but so is LISP and Scheme, which have completely different approaches.
And FP paradigms are more and more common. List comprehensions in Python are just bog standard adoptions of map and filter higher order functions from functional programming.
Not a panacea by any means. Sometimes it's harder to apply to general business programming in a meaningful and useful way - immutable objects aren't necessarily the best fit for data objects, to my mind anyway. Applied correctly and maybe less-than-completely the patterns and thinking from functional programming can be a good thing - but I'm not really a fan of pure functional programming and prefer the hybrid approaches like Scala.
}#q NO CARRIER
Yes, it means your functions aren't allowed to have side effects (i.e., all parameters are passed by value and the only result is the value returned to the caller).
Personally, I like it because it's a good way to manage complexity -- kind of like the encapsulation of object-oriented programming, except applied to the verbs instead of the nouns.
"[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz
Are the people who won't stop talking about it.
“Common sense is not so common.” — Voltaire
Functional languages are great for highly parallelized computation because well-behaved functions don't have side effects, and that eliminates entire classes of race condition and locking issues. Functional languages are also good for abstracting higher-order patterns, since you can manipulate data and other functions without having to care about their lower-level details. Specific functional languages like Scheme, where code and data share the same form, are great for creating custom syntactic structures and writing self-modifying code.
If you aren't doing any of those types of things, then functional programming may seem pointless to you, and that's OK. But every developer should be aware of the tools available to them in case the day comes when they might benefit from using them.
Sometimes, but just like Object-Oriented Programming it sucks when it's used as The One Paradigm To Rule Them All.
Preferences: Use OOP for GUI, and FSP (functional/structured programming) for services/backed. Use round pegs in round holes.
You can do a functional style of programming in just about any language, but using a true functional language brings you some added benefits.
Immutable data and pure functions make reasoning about your application so much simpler because there is no external state. With the same input, your functions always produce the same output. Testing is easier, debugging is easier, designing is easier, refactoring is much easier.
Another way to think of functional languages vs procedural, is describing to a computer how data moves through your program vs telling a computer what to do step-by-step.
A properly placed apostrophe has its virtues as well. it's means it is.
Or it has.
It's amazing that people that can learn dozens of languages all more complex than the previous can't seem to grasp the humble apostrophe.
I violently agree. The rule is very simple: If you mean "it is" or "it has" then you can write "it's". Otherwise, it is "its". Why so many out there seem to be unable to comprehend such a simple idea is something deserving of a study.
The best functional programming to me, is the kind being integrated into various primarily procedural languages. I use it daily in C# at work, and find it invaluable in performing complex transformations on data. Python, C#, etc. have the best of both worlds -- the choice to use whatever is best for your situation.
I'll expand further, maybe to start an interesting conversation because I'm sure someone will disagree: purely- or mostly-functional languages are the original hype-driven languages. A lot of people say they're amazing, but don't actually do anything useful with them. Sure, some are making great apps with them, but they're clearly the exception. At the end of the day most of the people I've talked to who preach about how awesome their favorite functional language is have only gone skin-deep. Their experience is limited to the academic or experimental, and has never gone into the practical.
The few times I've tried to really master these languages, I've been left with no epiphanies. I've found it extremely useful for some problems, like data processing mentioned above. But for most everything else, it doesn't get me anything useful. On some level it is nice having the flow of immutability -- it "feels" right, like you've discovered something special. The same way adding an extra layer of abstraction on top of something might feel. But when I'd look back on it and ask myself what I gained from having it, there's really very little to be found. It is, mostly, a dogma.
But it should not be The Only Way to approach a program - unless you are Truly One with the Tao.
Unless you are a total newbie who has only been exposed ot one tool, or a hypothentical/mytical code-master-of-all-code-masters who is "Truly One with the Tao," then you know there is no "Only [one reasonable] Way" to approach a program/problem, at least not one of any reasonable complexity.
Knowledge is how to play a game, intelligence is how to win, wisdom is knowing what game to play.
All programming paradigms have useful abstractions to offer. Eventually, they will all come together. Object orientation is great, until one overdoes it in design pattern hell. Likewise with functional programming. There are great many ideas in academic programming languages that will be made more accessible and integrated into mainstream programming languages. Functional programming is a dead end only in the sense SmallTalk was a dead end. People may not use SmallTalk much today, but its ideas live on in nearly every language we use today. Functional programming is here to stay. It won't replace imperative and object-oriented programming, but will add to them.
First and foremost, programming languages are for people, not computers. So if regular programmers who form the bulk of the workforce can't grok them, the languages need to be fixed, not people. Haskell is too hard for most. But it has many wonderful ideas that can be distilled into simpler forms and adopted and integrated elsewhere. Python got list comprehensions from it and perhaps the indentation.
C# is absorbing some features and Java is doing that less elegantly. Scala is a good balance and has already established itself. But people still find the type system complicated. So there are attempts to bring forth a simpler Scala - Kotlin, Ceylon etc.
We all agree that things like compact syntax, first order functions, lambdas, streams, type inference etc that functional languages pioneered, belong in every language. We still haven't sorted out how to make more advanced type systems, provability, strict programming without side effects etc more approachable. We should not need to have this much trouble explaining what a monad is or isn't. We'll get there, eventually.
The rule is very simple: If you mean "it is" or "it has" then you can write "it's". Otherwise, it is "its".
Unless you are using the word out of context: There are too many it's in this discussion, don't you think?
Knowledge is how to play a game, intelligence is how to win, wisdom is knowing what game to play.
If a programming language is functional by design I can image that it will also be optimized as part of the development. But does anyone know what happens if functional programming concepts are added to a non-functional language? Is there also any performance merit besides enjoying the merits of functional languages as a user? Or does it have performance implications due to the non-functional nature of the language?
When I was learning about functional programming in college, I got about as far as learning about the avoidance of side effects, at which point I started asking myself, "how would one write a video game in an FP language if you're not supposed to e.g. update the player's on-screen position in response to a keystroke"? The answer I got was to either generate an entire new game-state for each update (which seemed unwieldy), or work around the problem using monads, which admittedly I never really understood. I went back to procedural programming since that looked like the more straightforward way to implement the kinds of programs I wanted to write.
My question now is, do people ever actually write video games using functional programming? And if so, how would an FP-based arcade-style video game realistically handle things like updating the state of the player and the monsters at 60fps, as the game progresses?
I don't care if it's 90,000 hectares. That lake was not my doing.
Asking whether you like functional programming is like asking whether you like phillips head screwdrivers.
I do not. Give me JIS screwdrivers any day.
sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
So if regular programmers who form the bulk of the workforce can't grok them, the languages need to be fixed, not people.
I know what you're saying, but there's a real danger here that the industry will find itself caught in a local extremum. An engineer of 1880 could easily have said that if regular engineers who form the bulk of the workforce can't understand this "electricity", then it needs to be fixed to conform to the world of steam.
The worst thing we can do as an industry is think we know what we're doing. And in a sense, we're already there.
sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
I don't think Iranian is a language.
"being cleaver"
Beaver? I told you not to hang around with the Eddie Haskell.
Yes, it means your functions aren't allowed to have side effects (i.e., all parameters are passed by value and the only result is the value returned to the caller).
I generally program that way in Python. I'll have to add functional programming language to my bucket list.
emil post's rewriting systems were tres reserche, too.
and mccarthy's "lots of tiny parentheses", as well.
Asking whether you like functional programming is like asking whether you like phillips head screwdrivers.
I do not. Give me JIS screwdrivers any day.
If you like JIS, you like Phillips. If you like Phillips, you may not like JIS. It's like rectangles and squares.
lucm, indeed.
I didn't like functional programming at first, but after using it for a while I started seeing the benefits of things like first class functions and immutable state. Even if you don't think functional programming is a silver bullet, it's worth learning and understanding how the functional approach differs in solving programming problems. Adding another way to think about programming problems to your arsenal isn't a bad thing.
I tried a websearch the other day on "functional programming considered harmful" and found remarkably few hits. If anyone is so inspired, there's an opportunity there to gain some fame while earning the emnity of the hordes of javascript kids and half of the Computer Science digirati.
The only time I've tried functional programming was during a class at the Uni. My memory from that class, was that when I finally got a progam through the compiler, it simply worked. No flaws or bugs at all. Of course, a single class doesn't make me qualified to neither promote nor dismiss it. Having said that, I prefer Python for simple PC-based tasks, C (or the non-obscure parts of C++ if the resources permits) for my daily work as embedded designer on ARM Cortex-M and smaller MCU's.
https://wiki.haskell.org/Game_Development
Programming is about translating what you want a computer to do into a set of instructions that the computer understands that mean the same thing.
That is half of what programming is, at most. The other half is, at least, making that set of instructions easily understandable by another human being. Your code will be read thousands more times than it is written, and readability is far more important than your statement suggests.
Anyone who is all for functional, OO, actor-model, etc programming is incompetent. Different paradigms work in different scenarios and being a good programmer is mostly about knowing what to use when/where.
For that to be even ostensibly correct, you're missing one single quote mark and some double quotes, e.g.
"There are to many 'it's, don't you think?" he said.
And even that is arguable, because those aren't really apostrophes; they just happen to use the same key on the keyboard, typically.
With only two exceptions, the plural of any word is always spelled with an 's', not an apostrophe followed by an s. The exceptions are:
And even then, those exceptions might depend on what style guide you go by.
Check out my sci-fi/humor trilogy at PatriotsBooks.
My first encounter with both OO and functional programming was Clipper 5.0, the dBase compiler. It incorporated parts of OO and parts of functional programming, lambdas actually, called code blocks. Both have their uses.
I started using Scala in 2011. The tooling was very rough at first, but I really liked the language as an alternative to Java. Since then I've adopted a progressively more functional style in Scala, and found it to be a very natural way to think about code. Some of my code is multi-threaded, and using immutable data structures, I find I spend a lot less time worrying about locking. And the tooling is now fairly reasonable in my opinion. Scala's interoperability with Java was a big selling point in the early days, but the Scala ecosystem is now getting to the point where it stands on its own rather well.
A really great development in the Scala world is Scala.js, which transpiles Scala to JavaScript. I despise JavaScript for any development larger than a page of code, so Scala.js was a welcome relief. If you work on large JavaScript apps, do yourself a favor and check out Scala.js. I look forward to the day when WebAssembly matures enough to be a target for Scala compilation. Hopefully then JavaScript will fade away, and someday it will just seem like a bad dream.
I've yet to see realistic examples of improvements, at least for domains I work in. Those pushing FP either invent contrived "lab toy" circumstances where FP shines, use vague buzzwords that don't describe any concrete benefit, or merely expose the weakness of a particular language or API design (such as Java's poor OOP model).
If you want to convince people, show them realistic examples and explain the benefits in concrete and measurable terms. Is that asking too much?
They may say, "If you use it long enough, you'll finally get it"; but there are so many tools and ideas competing for our time that I'll have to ask for more up-front evidence, if you don't mind.
Table-ized A.I.
It is helpful in context of walking data model trees in OO languages. It also allows to write stateless code which supports parallelism. It helps with reactive systems including UIs and PLCs. It also sucks in some high performance areas. When people think Optional is a good idea to avoid if then else as code construct and replace it by function calls.
In my experience FP style (in python), makes me spend lot more time in the design phase. The emphasis is on data/data-structure more than the code/algorithm/operations [the spotlight of imperative languages]. You start thinking more about how your data gets transformed from input to output. I felt this way of separating data representation from the code/operation lead to more robust code; also much faster implementation phase. FP surely changes the way you think at a higher plane of the problem at hand.
A triple "it's" / "its" error in one sentence. Good work, AC.
I have found two ideas that came from Lisp that are invaluable.
Minimize side effects in most functions. Any effort to reduce side effects will be repaid tenfold the next time you have to fix a bug or add a feature.
Keep data objects immutable. This is the key to the easy life if you have to do concurrent programming (and who doesn't these days?).
Play Command HQ online
It's just another framework we've had for ages..
I see it with so many languages, all they do is add functions we already created in the past as standard options. It's really nothing new..
A problem with a lot of newer frameworks, is that a developer doesn't have any idea anymore as how it actually works underneath, so if something doesn't work they can't figure out why as they don't have the understanding (doesn't mean you have to know all the ins and outs).
Problem these days is, there are sooooo many frameworks, and everytime a new framework pops up it'll be a favorite for a while and then we all have to move over to the next new hip framework even if it doesn't actually add anything new to the previous one.
I love it how functional programming lovers show examples of a few lines of code and say "see i solved this difficult problem in just 5 lines of code". Then you ask what the other files are and they have written 10,000 lines of code for all the related functions.
Yea abstracting is not something that only works in functional languages guys.
Try writing sets of asynchronous Jasmine tests that use promises, lodash iterators, success callbacks and other things of that nature arrays and madness swiftly follows.
1 character names for types are not good
Says who?
All localized variables and types in my programs have 1-character names, and its for multiple good reasons including that because you can see that something is only 1 character at a glance, that therefore you know for sure that it doesnt have much if any outer scope with that very same glance.
"His name was James Damore."
The actual language is called farsi (new persian).
Functional programming is a fine enough paradigm. It can be very educational to look at a problem from a different perspective? imperative, object-oriented, functional, logical, etc.. Hence, yes, functional programming is a very useful thing. I think every programmer should give functional programming a try.
However: Mixing paradigms within a programming language makes code more difficult to understand, and generally leads to language bloat. It's worse, when the underlying language fundamentally cannot support the paradigm.
Prime example: Java + Lambdas. Java does not support working with code the same way you work with data, which is what functional languages are all about. With reflection, Java allows limited inspection of functionality, but no manipulation. Java lambdas are a way of faking one aspect of functional programming: the ability to pass code as a parameter. However, you aren't actually passing code as a parameter. If you were, then you could alter the value of that parameter at runtime, like you can any other variable. Instead, you're just letting Java fill in some blanks at compile-time, because the interface you select has only one abstract method. This is syntactic sugar that kinda, sorta looks like functional programming, but actually isn't. As such, Java lambdas are a really stupid idea. Anyone who has used them thinks they've done functional programming, but they actually have not.
Enjoy life! This is not a dress rehearsal.
That's a cutting remark!
Confucius say, "Find worm in apple - bad. Find half a worm - worse."
So is knowing and understanding it.
FP basically forces you to do multiple steps in one and trains your brain to think faster. Getting rid of state wherever possible is a neat thing too and enables more complex programms and routines that are less error-prone and more vertasile.
As long as you can wrap your head around what your doing FP is great. I've made a habit of using it whenever I can. ... Although sometimes I'm just to lazy or tired and start wittling about with variables again.
We suffer more in our imagination than in reality. - Seneca
I maintain a large-ish enterprisey system, most of which is written in C#. I use the functional features of C# every day. However, I would caution you against lumping all functional features under a single heading of "functional programming" because you can look at each feature independently and decide whether you want to use it.
For me, I definitely use immutability, both in combination with dependency injection for my service classes, but also in many of my data structures. For instance, I might have a module that pulls a bunch of state from the database and then organizes it into a projection, such as a forecast of material usage. That forecast is immutable. I then (optionally) have the ability to cache that either locally in the program, or cache it to the database, but when I bring it back it's still immutable, so that data with that ID never changes, and none of the consumers of that data need to worry about it changing. In some cases that means I can safely split the further processing of that data across multiple threads rather easily.
Also, LINQ is really just a ripoff of Lisp's S-expressions, and I find it extremely useful. If I have a list of anything, and I need to manipulate it into another form, then LINQ allows me to do that without loops and with less complexity. I generally still use loops for modifying data.
LINQ is really a combination of three features: 1) functions as first-class citizens, 2) lambda expressions/syntax, and 3) closures. These are very useful on their own. Being able to take a function as an argument is extremely powerful, and being able to define a function inline when you call that method, and have it capture values from outside that function in the form of a closure -- very powerful.
That doesn't mean there isn't a use for imperative programming, but when I see a colleague filtering a list of objects with a foreach loop, I just cringe. Just use a .Where() clause! Don't be afraid of functional - use it as one more weapon in your arsenal.
"I have never let my schooling interfere with my education." - Mark Twain
fundamental difference between a map or an iterator in terms of how they execute.
So the question becomes one of aesthetics - and that must, inevitably, have a subjective aspect to it. Those who love the functional approaches will find them more pleasing, those who prefer the OO approaches will prefer those instead.
And some, like me, will mix and match them according to what looks better for the piece of code I'm currently writing - much as I choose between a for-loop or a list-compression based mostly on how long the list-compression is. Anything over about 60 characters and a for-loop is simply more readable and easier to debug.
Unicode killed the ASCII-art *
... dysfunctional programming is way more used in the real world..
SeqBox
Eric Lippert, a former Microsoft employee and one of the main designers of the C# language and someone who understands and appreciates functional programming (having brought many functional paradigms to C# such as lambdas etc.) responded to the question "Why hasn't functional programming taken over yet?" on StackOverflow, which for me, sums up everything I feel about functional programming.
I've quoted Eric's answer below, but the TL;DR is that I believe the future is neither purely functional, nor purely OO, but some hybrid of the two.
Because all those advantages are also disadvantages.
Stateless programs; No side effects
Real-world programs are all about side effects and mutation. When the user presses a button it's because they want something to happen. When they type in something, they want that state to replace whatever state used to be there. When Jane Smith in accounting gets married and changes her name to Jane Jones, the database backing the business process that prints her paycheque had better be all about handling that sort of mutation. When you fire the machine gun at the alien, most people do not mentally model that as the construction of a new alien with fewer hit points; they model that as a mutation of an existing alien's properties.
When the programming language concepts fundamentally work against the domain being modelled, it's hard to justify using that language.
Concurrency; Plays extremely nice with the rising multi-core technology
The problem is just pushed around. With immutable data structures you have cheap thread safety at the cost of possibly working with stale data. With mutable data structures you have the benefit of always working on fresh data at the cost of having to write complicated logic to keep the data consistent. It's not like one of those is obviously better than the other.
Programs are usually shorter and in some cases easier to read
Except in the cases where they are longer and harder to read. Learning how to read programs written in a functional style is a difficult skill; people seem to be much better at conceiving of programs as a series of steps to be followed, like a recipe, rather than as a series of calculations to be carried out.
Productivity goes up (example: Erlang)
Productivity has to go up a lot in order to justify the massive expense of hiring programmers who know how to program in a functional style.
And remember, you don't want to throw away a working system; most programmers are not building new systems from scratch, but rather maintaining existing systems, most of which were built in non-functional languages. Imagine trying to justify that to shareholders. Why did you scrap your existing working payroll system to build a new one at the cost of millions of dollars? "Because functional programming is awesome" is unlikely to delight the shareholders.
Imperative programming is a very old paradigm (as far as I know) and possibly not suitable for the 21th century
Functional programming is very old too. I don't see how the age of the concept is relevant.
Don't get me wrong. I love functional programming, I joined this team because I wanted to help bring concepts from functional programming into C#, and I think that programming in an immutable style is the way of the future. But there are enormous costs to programming in a functional style that can't simply be wished away. The shift towards a more functional style is going to happen slowly and gradually over a period of decades. And that's what it will be: a shift towards a more functional style, not a wholesale embracing of the purity and beauty of Haskell and the abandoning of C++.
I build compilers for a living and we are definitely embracing a functional style for the next generation of compiler tools. That's because functional programming is fundamentally a good match for the sorts of problems we face. Our problems are all about taking in raw information -- string
I know squat about Functional Programming. But I'm told that Python's List (and generator) comprehensions are a functional programming concept. Input a list, perform an operation on all or part, and output an altered list. Not terribly readable IMO, but otherwise quite likeable. I find myself using them quite a lot.
As for stuff like closures. The explanations I've read tend to be utterly opaque. Sort of like a color-blind individual trying to explain the color green. I'm not sure if the problem is me or the explainers. After a lot of reading, I think I sort of might understand how closures be done in Python. But it's sort of like reading about how to build a working mechanical arm out of toothpicks. Interesting, but I'll be damned if I can envision a situation where I might want to do that.
You can't see ANYTHING from a car, You've got to get out of the goddamned contraption and walk...Edward Abbey
You may have misunderstood the previous poster's use of "poor coder."
I read it as "unfortunate coder", not "incompetent coder."
I could certainly be wrong. Perhaps clarification will be forthcoming.
I've fallen off your lawn, and I can't get up.
Would you consider unions in c a "means to circumvent the type system" as compared to a language with strong up-front typing?
Unions are certainly a very powerful, useful, and concise tool for manipulating data across type boundaries. If you don't have them, in trying to accomplish similar tasks as those unions make easy, in many languages you're going to be a lot more verbose, and likely a lot less efficient, than if you do.
I am assuming competence. Strong typing is a safety net. The need for such a thing varies with one's skill set. The fewer the participants, the more likely it is that the skill sets can be arranged to be similar. With larger teams, the need for safety nets almost always increases.
I've fallen off your lawn, and I can't get up.
This is the core mechanism of my text markup language. Once the specific built-in tokens are parsed out, they are immediately accessed via the language's function dictionary. This approach is quick, ultimately low-complexity, trivially extensible, and highly maintainable.
I've fallen off your lawn, and I can't get up.
IMHO, unit testing is a far, far more important aspect of advancing programming in general than are lambdas. Just my 2c. :)
I've fallen off your lawn, and I can't get up.
I would add to this that reducing the complexity by turning everything into separate functions tends to also increase what I call "opacity by non-locality."
Not only are some things hard, some things benefit from having the logic right there in front of your face; not in a header, not in some function elsewhere, not in a library.
Benefits in both comprehension, and so ease of construction, but also in execution time and smaller executables depending on just how smart the language is in constructing its own executables.
I've fallen off your lawn, and I can't get up.
Structs do, however, make the critical aspects of an object oriented approach practical in c. They can carry data, function pointers, etc., and they can be passed around.
I've been writing my c code like that since the 1980's. There are significant benefits.
I've fallen off your lawn, and I can't get up.
Where I work we only engage in dysfunctional programming.
((((((((((((I hate lisp too))))))))))
I've fallen off your lawn, and I can't get up.
I have never understood why the language is not considered a parody like the whitespace language. You cannot debug or change code when it is 90% brackets, and more than two to three ")))" brackets in a row and editing the nesting of something becomes really hard and error prone.
A proper language tries to evenly distribute the character usage evenly over a wide array of characters, such that the code is easily readable.
I have only seen a few examples in Scala, which replaced Java in my university the year after my class. But they were the least readable code snippets I have ever seen. It looked like they had replaced all the white space with brackets.
Troll is not a replacement for I disagree.
I can write certain types of algorithms much faster specifically iterating arrays and associative arrays/dictionaries faster for the purposes of transforming data sets. Functional programming typically is more optimized than a do-it-yourself algorithm. No sense re-inventing the wheel if you don't have too.
We'll make great pets
what i don't like is functional programmers!
Copyright (c) 1990 - 2014 Dice. All rights reserved. Use of this comment is subject to certain Terms and Conditions.
Programming is about translating what you want a computer to do into a set of instructions that the computer understands that mean the same thing.
That is half of what programming is, at most. The other half is, at least, making that set of instructions easily understandable by another human being. Your code will be read thousands more times than it is written, and readability is far more important than your statement suggests.
Writing a website in assembly language is a very useful and pragmatic skill to have. In fact, I encourage those folks that can do it to put it on their resume and see how many job hits they get.
We'll make great pets
Why so many out there seem to be unable to comprehend such a simple idea is something deserving of a study.
Why are there so many people that can not comprehend that writers completely know the correct form of usage but STILL make simple TYPING MISTAKES!!
And the damn typing mistake is not red underlined because it is a VALID WORD!
And no: proof reading does not make me see such errors, as I'm a whole word or even "whole sentence" pattern match reader.
(And in this text everything is red underlined because I can not make Windows 10 automatically detect the correct dictionary -- gosh this MS bullshit is so anoying ... my 20 year old Mac SE is better in EVERY regard than this windows nightmare)
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
Here's a document that explains functional concepts in Python. Seems reasonable:to me.
https://docs.python.org/2/howt...
You can't see ANYTHING from a car, You've got to get out of the goddamned contraption and walk...Edward Abbey
I've seen many of these "paradigms" come and go.
It's like someone coming up with a new way to make soup. New ingredients, new cooking methods, new ways to chop vegetables, new pots to put in in, blah blah blah.
In the end, it takes about the same about of time, tastes pretty much the same, and only refrigerates so many times before you have to throw it out.
When Fascism comes to America, it will call itself Anti-Fascism, and tell you to give up your guns.
Implementing functional programming needs to come at the right time for it to be effective. Until all of your programmers are following the internal style guide without exception, functional programming is not likely to take off. If people are still arguing over block style, forget getting them to agree on proper style for Lisp and the metric ton of braces.
I only look human.
My mother is a halfling and my dad is an ogre, so that makes me an Ogreling
CS61A, or Introduction to Programming, is a flunk out/weed out class at UC Berkeley. It is taught in LISP and is functional programming. Why? Functional programming runs counter to the way the majority of people think. Science says that functional programming is demotivating for the general population. So, what do you do if you have way more students interested in Computer Science than you have slots available? Easy, just make them pass a functional programming course.
CS61A is the only mandatory functional programming course at Berkeley. All other courses are in Java, C/C++, Python etc.
The only question one needs to ask about a computer language is this: can the language exercise the full functionality of the target computer? If the answer is yes then all such languages are interchangeable and logically equivalent.
Since scientifically speaking most people think in for/while loops and not function calls then procedural programming is the most common.
What have we learned?
Don't let Javascript and Hacker News fool you. Hacker News is predominantly a hang out for the functional programming crowd. This is a self selective audience. If you are not interested in functional programming then there is not a lot of content on Hacker News for developers.
Javascript is a bloody mess, especially with the Nodejs. A bloody mess is not functional programming. For/while loops are for more prevalent in Javascript then functional programming. At issue is all the callbacks for async event handling. Javascript is very poorly designed software because unless your async code is wrapped in monitors it is not proper async code. Promises? Pick up any programming text book on async programming and it will always teach you to wrap your async code in monitors/semaphores/locks.
I have a erlang team (over two years), and although it seems they work hard there is not much to show for it. Everything is written, then rewritten multiple times. Very ordinary things like web servers require extensive customization. Actually, lots of ordinary stuff requires custom implementation. The dogma and religious wars never end. It is difficult to staff qualified people. In short, many liabilities and it will be a long time before I sign up for another FP project.
Yes, it means your functions aren't allowed to have side effects (i.e., all parameters are passed by value and the only result is the value returned to the caller).
It's quite a bit more than that, at least if you're talking about pure functional programming. You also have to get rid of most all of your old notions of flow control. Imperative programming is about defining sequences of steps, some of which are conditional. Functional programming is all done with nested transformations; there are no sequential steps, there are no branches, there is no iteration.
If this sounds freakish and impossible to someone raised on imperative programming paradigms... yes, it is. Functional programming requires thinking in an entirely new way. It's a very powerful tool. I'm not sure it's the best tool for the systems I build (though I'm also not sure it isn't), but at a minimum it's a useful way to think about code construction. Every programmer should spend some time learning it.
Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
At it's simplest. The first instruction of a function program executed, the PC register is changed and that's that. The state of the machine is changed. Claiming to be startelss is just a fictional abstraction. Moreover most programs are all about state ( eg. databases ). State is something that functional programmers have been trying hard to isolate for a long time, inventing such monstrosities as monads ( which BTW are easy to understand when you don't use category theory ). But I would really like to see something like a word processor written in a purely functional language with monads like Haskell. Then someone take the % of the code spent creating stateful monads ( such as IO or Option ) vs nonmonadic code or stateless monadic code ( like Lists ). I suspect that on averaage over all the programs in the world, 90% of the code ( via code, execution time, or any other size metric ) is spend into stateful monads and 10% in the rest of the code.
I always want to get code that works, and better yet that works right after successfully compiling. Haskell with its functional style and rigid type system helps me catch the multiple errors that inevitable end up in my code as I write it. I have done multiple programs and libraries in Haskell and I’m pleased with the small chunks of expressive code that come out of these efforts. Sometimes I have to write verbose monstrosities that do very little in Java. I always dread going back to it. I write many more bugs in Java that I do in Haskell, and fewer get caught at compile time. A Java IDE is where both my productivity and fun go to die.
Functional programming is getting better. I use lambdas in C# all the time, sometimes in Python too (although I don't like the syntax), and I've tried them in Java. In C#/Java/et al they are fabulous ways to focus on the Functionality and not the Implementation (what the heck is this FOR loop doing?).
Pure functional has problems that will be solved. Jet.com is based on F# (the whole website and backend - yes a bit of C# here and there). Now could be the time to jump in - while being aware that patterns and practice are an emerging area and there will be growing pains.
I've been using F# and R for over a year now. F# caused me to suffer from a problem that early OOP/C++ programming had - methods/layers that hid too much and made debugging difficult because it wasn't clear where it went wrong. Plus the syntax of these languages can be confusing, and procedural languages (C#/++/Java) work the way we "think" "step1 - do this, step2 - do that" Functional focuses on the end product and not the steps in between. Beyond different syntax, we need to think differently.
I've found myself passing too many arguments "down" to the layers (again - something early OOP suffered from). The promise of altering the lower implementation layers without affecting top-level code hasn't panned out. I've had a bit better luck with R but the problems I'm solving are different. F# has been a "real" program and R has been computation of stats (grab data and compute min/max/avg). OOP solved it through better patterns such as ambient properties and policy injection, possibly OCP (which is NOT a functional solution). I'm finding the readability of code to be difficult (esp this Javascript nested stuff -- seems like using the wrong tool for the job, as in, I want to program like this and let's' see what's in the web toolbox... Javascript it is).
While I like F# my biggest mind-bender has been around function composition. The idea of magic params that the runtime simply solves causes a lot of "magic" to occur that isn't obvious to the coder. Yes - shorter code. However, the next person must spend time reading and understanding the code before being able to make changes that doesn't break the implementation. Again - the OOP problem. To read an F# function and wonder "where'd param 3 come from?" or "where *does* param 3 come from?" Quite possibly new patterns that must be learned.
So I say - give it a try. Learn a new language.
I work far more with SQL than programming languages really, but I do work a lot with doing operations on large data sets so I definitively try to avoid looping through a million rows. I use in-memory or temp tables to chain operations without storing state. And that's all neat and well, but without a ton of state in between those set operations to say what's ready, what's running, what's done etc. I'd go nuts. The functional bits are the stretches between the state almost like barriers in computer shaders and other synchronization methods. A pure functional application well I couldn't really imagine it unless it read one file as input and spit out a result, it just flows through the whole application. Every time I try to understand state in FP my head hurts.
Live today, because you never know what tomorrow brings
"High brow" programming has never proven itself in practice for multiple projects. There's never been a case where top-notch, highly-educated programmers are put into a single organization such that it consistently out-competes the "medium-brow" shops. They may be paid more than average, but in theory they'd be far more productive using high-brow techniques such that it overshadows their higher salaries.
Some bring up Paul Graham and his e-stores company, but that was a one-shot deal. Once the company became established it abandoned Lisp. Quick-to-market entrepreneurial may benefit from it, but I'm talking rank and file projects.
Related discussion:
http://wiki.c2.com/?IfFooIsSoG...
Table-ized A.I.
No? So you're saying you prefer dysfunctional programming?
I'll see your senator, and I'll raise you two judges.
> I'm not sure if the problem is me or the explainers.
I'm fairly sure it's the explanations, which tend to mathematically define them, rather than showing what the heck they are are what they are good for.
I noticed that the other day looking for good explanations of the normal forms in relational databases (sql). Most of the explanations I found were crap. Rigorously correct, and entirely useless to someone who doesn't already fully understand them.
My kid is two. When I wanted her to know what a "horse" is, I didn't start with a rigourous, formal definition of "horse" as distinct from all other species. I showed her a horse, so she could see what it is, then I showed her someone riding a horse, so she can see how it's used. I wish more comp sci people had basic competence in explaining or teaching.
Mostly because when I was taking it in college 20 some odd years ago all the code they gave us as example basically tried to do everything in one line of code. I mean damn, maybe if your terminal gave you a 50,000 volt shock for hitting the enter key I could understand it but it made debugging anything a complete pain. (Well that and the fact you had to have the absolute perfect number of parenthesis. One too many or few and watch the app crash.)
Did you know 80 to 90% of the moderators on slashdot wouldn't recognize a troll even if one dragged them under a bridge.
I understand this is stupid but I would like to know... have a look at:
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Look through the inititial text and get an idea. Then jump to the C code (not functional).
Then look at functional implementations: C++11, Python, Closure, Haskell, PicoLisp, Python, Scheme, Swift.
Look at Scala: 2 ways: functional (recommended) and procedural. Look at it.
What do you see?
What do you think?
Object oriented design is here to stay. Functional programming has it's place, but as little more than one off event handlers, I wouldn't call it a programming paradigm. Like interfaces, it's useful, but it's more applicable in some situations than others.
Put it this way, if someone told me OOP was dead, I'd fire them because it would indicate to me that they didn't understand OO and would likely be resistant to understanding it.
*** *** You're just jealous 'cause the voices talk to me... ***
At about age 3 months the child learned "there" or "not there" for things. They could distinguish 0 from 1. Functional counting reduces to an even easier algorithmic skill learned even earlier
In Python you would rarely want to do it. I'll give you some simple examples.
items = [1, 2, 3, 4, 5]
def sqr(x): return x ** 2;
list(map(sqr, items))
Now imagine this were legal:
[1, 2, 3, 4, 5](map(**2,items))
The **2 is a closure
I love how it's done in Ruby. It's compact and yet readable, unlike certain other older languages known to include many paradigms, including OO and Functional.
Brian Fundakowski Feldman
If you think about it, those are inevitable consequences of the constraints I mentioned. However, it's good that you highlighted them.
Yep, both recursion and constructs like map/filter are incredibly useful (even in procedural/OO languages) once you get the hang of them.
"[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz
Just guessing what AC means, but assuming he's talking about Java, enum's in Java can take arbitrary values (they're just instances of a class, and so can have as much state as you'd like, including lambdas). It lets you do the equivalent of creating an interface with one method, and a class that implements that one method specifically for each enum, without all that clutter and boilerplate. But it's a bit hacky, and best kept to small, self-evident lambdas. Java-style enums, aka "class enums", let you avoid a lot of switching in general, since often you were just getting some constant value associated with each enum value.
Socialism: a lie told by totalitarians and believed by fools.
I see a ton of comments here from people that clearly don't understand what functional programming is, or they don't really get it. If you consider yourself a programmer, go to Project Euler and do the first 20 (or 50) problems. Use whatever language you like. You have to do them, because you need to solve them to see all the other solutions.
Look at the solutions, in all the different languages, and compare. Not just for speed, but the design. Take a good look.
For all the BS about Groovy not being functional, if you look at partial implementations, Groovy is just as functional as Scala. And better yet... it is 100% compatibale with Java; Take ANY Java class and change the extension to '.groovy' and it will compile!
This is my sig. There are many like it but this one is mine.
** is a function of two variables. The 2 is coming from a different context. **2, as a squaring function is a closure. No need to be complex about closures.
** is a function of two variables. The 2 is coming from a different context. **2, as a squaring function is a closure.
(**2) is a Haskell-style "operator section" which would be shorthand for "lambda x: x**2" in Python. This lambda has no free variables and thus is not a closure. An example of a closure would be the second lambda in "lambda x: lambda y: x**y", which closes over the free variable "x". You can also do this without lambdas:
def pow(x):
____def curried(y): return x**y
____return curried
# returns closure of lambda y: x**y, capturing x=2
f = pow(2)
# returns 2**4
f(4)
(Pretend the underscores are spaces.) The important part is that the function you are capturing includes references to free variables inherited from its original context.
"The state is that great fiction by which everyone tries to live at the expense of everyone else." - Bastiat
I was treating (**) as your second case, ignoring the (**2) as a specific function. Remember the idea originally was to show a simple example of the concept for Python.
I have examined the concepts and languages involved in functional programming and I do not see their value. Most of my work is split between C and shell scripts with random PHP, SQL, etc. peppered in as necessary. My question is simple: what can functional programming do for me, in practical terms? Including a real-world example is mandatory to answer the question. I always see platitudes regarding either "elegance" or "you'll have to think differently" but neither is an actual benefit. I don't need a hammer that is hard to use and makes me think about the nature of hammers and their usage; I need something that is efficient and straightforward when I decide to forcefully attach two things using nails.
As far as I can tell, functional programming is only useful as a thought exercise...which means that (compared to "uncool" but widespread languages like the C family) it's not useful when you actually want to get something done.
So you were treating (**) as the free variable? That works, provided the operator actually appears as a function argument or local variable in an enclosing function context. References to global definitions do not create closures in Python. (The value of a global variable or function definition is looked up at each call, not captured as part of the lambda.) However, in that case you can't really refer to (**2) as "the squaring function" since (**) could do anything, not just exponentiation.
"The state is that great fiction by which everyone tries to live at the expense of everyone else." - Bastiat
Example? I've only seen examples that expose weaknesses in Java and/or its GUI libraries.
For example, if the distinction between on object and class were blurred, then each GUI push-button could and should have an OnClick method. (Language could include an option to add or change the method away from object declaration.)
Instead, one has to "register" the on-click code with a "listener" via a lambda. Why the fock should a typical coder have to care about a fricken GUI listener? That should be under-the-hood guts, or at least something you only care about (mostly just inspect) if there is a tricky bug. The coder mentally associates the on-click behavior with its button, and the GUI API should reflect that common sense. Java's doing it wrong; lambda's are merely a band-aid over bad design in that case.
"We forgot to think this through so instead we randomly shoehorn behavior into the gui via lambda's"
I've seen other "justifications" for lambda's that are usually a kludge over bad languages and/or libraries.
Table-ized A.I.
Yes
Show me the code --Linus
Casteism
The industry learned the hard way that OOP works well for some things but not others. For example, OOP has mostly failed in domain modeling (modeling real-world "nouns") but is pretty good at packaging API's for computing and networking services.
The industry may also learn the hard way where FP does well and where it chokes. Some understandably don't want to be the guinea pigs.
Table-ized A.I.