News for hackers. Stuff that matters.
Re:Why functional programming matters by patrickmn on Tuesday April 18, 2017 @08:53AM (#14138386)
Why compose classes, abstract base classes, etc. when you can compose simple functions!

It's true that abstractions in functional languages can seem foreign and hard to understand, but generally they have some purpose, being grounded in mathematical practice. OO abstractions and patterns OTOH, taught essentially in "elementary school" which possibly makes them seem easier to understand, do a very poor job of solving more problems than they create.

Learning a functional language is often a transformative experience that lasts throughout a career, whether you even use functional languages or not. It might make you do something as simple as partitioning which functions have side effects and which don't, even if the type system doesn't enforce it. Or use a form of quick/fuzz testing, even if it's not the standard test suite. Or make parts of the data immutable for scalability, auditability, etc. Or...

There really are few things as satisfying as developing a large codebase in a functional language. A lot of the frustrating maintenance work just goes away. But even if you don't, functional principles can yield similar benefits in imperative languages.

Re:Why functional programming matters by acdha on Tuesday April 18, 2017 @09:56AM (#14138811)
> It's true that abstractions in functional languages can seem foreign and hard to understand, but generally they have some purpose, being grounded in mathematical practice. OO abstractions and patterns OTOH, taught essentially in "elementary school" which possibly makes them seem easier to understand, do a very poor job of solving more problems than they create.

This kind of sweeping unsupported assertion is actively harmful for FP evangelists. Anyone who isn't already a fanboy is most likely going to read that and say “clearly this person has no idea what they're talking about. [close tab]”.

If you want to make a productive form of this argument it'd be better to focus on discussing why the mathematical abstractions are so much better with comparisons to their actual recommended OOP counterparts. The points you mentioned about things like side effects or immutability are good but you need to not give someone a reason to go away before getting there, especially since there are going to be common tasks like I/O which are _not_ going to look like an improvement for anyone who isn't already on-board.

Re:Why functional programming matters by patrickmn on Tuesday April 18, 2017 @10:52AM (#14139270)
> This kind of sweeping unsupported assertion is actively harmful for FP evangelists. Anyone who isn't already a fanboy is most likely going to read that and say “clearly this person has no idea what they're talking about. [close tab]”.

That seems as much an unsupported assertion (i.e. opinion) as what I wrote.

I don't think it's useful to try to write a comprehensive essay with no ambiguity every time I comment, and I don't have the time. Doesn't mean I don't believe the things I say. :)

If you decide to close the tab because I said functional programming languages are much better at abstraction, that's too bad, but it's not exactly an unsupported assertion--and I'm not trying to sell you anything anyway.

If it helps, most of my FOSS stuff is written in Go, a language Haskell fans generally vehemently dislike for "ignoring 30 years of PL research." I actually like Go for a similar reason I like FP: It does away with a lot of the bad abstraction (classes) and emphasizes the good (interfaces.)

Re:Why functional programming matters by acdha on Tuesday April 18, 2017 @11:47AM (#14139815)
The difference is that you're dismissing the entire field of mainstream software development for the last couple of decades as “elementary school” level abstractions which “do a very poor job of solving more problems than they create”. A strong majority of working programmers are familiar with those concepts because they were taught those concepts in schools, by industry experts, and see them used by platform developers and vendors.

FP is not that pervasive and anyone trying to make the case that it's better across the board has to address that familiarity gap. Try to think about, say, the average Java or C# developer working on a large project. They aren't spending their day saying “OOP is terrible” and when you say something is better because it's “grounded in mathematical practice” that's really non-obvious to someone who's thinking the main way their life would improve would be if they could get the business stakeholder to make a decision and stick with it for more than 24 hours, stop using Oracle products, etc. Talking about avoiding shared state and side-effects, going beyond Java-level typing to make refactoring safer, etc. is a lot more useful since those probably are things they spend time on regularly.

Re:Why functional programming matters by patrickmn on Tuesday April 18, 2017 @11:54AM (#14139863)
I don't disagree that somebody who knows OOP but not FP needs a lot more information than I gave. Where we disagree is on the notion that I need to explain everything in detail when there are fountains of material out there. If anything, the purpose of my comments is to make you think, "Is it hyperbole, or is he on to something? Maybe I should look into this further."

I was an imperative programmer for a decade before I looked at functional languages, and it was because of glowing but unfamiliar praise that I looked deeply in the first place. Now I know that a lot of that praise was warranted. Everyone's different!

Also, as I noted in another comment, the "elementary school" comment was not meant to imply that it's simple--alas, one of my main gripes with OOP is that it isn't simple in the ways it needs to be--just that it's something you're almost certainly exposed to early on, so it quickly becomes what's familiar.

Re:Why functional programming matters by VladimirGolovin on Wednesday April 19, 2017 @02:22AM (#14145878)
Just wanted to note that the "elementary school" comment in the original post rang true with me. When I was learning OOP, my first program was literally about animals (cows, chicken, sheep) making sounds. A cow says "Moo", a sheep says "Baa", a chicken says "Cluck-cluck", an Animal says "Error: this method shouldn't be executing" or something.
Re:Why functional programming matters by novembermike on Tuesday April 18, 2017 @02:56PM (#14141775)
What he wrote is a comment in a forum, not an article. This is his opinion.
Re:Why functional programming matters by acdha on Tuesday April 18, 2017 @04:19PM (#14142504)
Yes. Note that I did not say it was wrong or that he shouldn't be allowed to hold it, only that the style in which it was expressed seemed unlikely to be effective for people who didn't already share that opinion.
Re:Why functional programming matters by Raknarg on Tuesday April 18, 2017 @01:09PM (#14140625)
Honestly I'm not sure if OO is actually easier to understand than FP. I remember when I started programming it was a crappy but simple language called Turing that was procedural and had support for objects and pointers.

We weren't really taught classes in my high school course, so everything we did was entirely imperitive. I came across a problem where I had about 20 different entities in a game who all had a special way of updating during each tick, but I didn't want to have to write a switch statement for each one. I looked up "How to have an array of functions", and without knowing it at the time I was trying to implement first-class functions in this language which it just so happened to have.

From there it's easy to see how once you understand the concept of first class functions, many FP concepts start to fall in line, and by the way the language was set up it was difficult to use side-effects in this language, generally you use a function to output to the screen or to return a new resulting value. In fact when it finally came around to learning about classes, I had a very difficult time understanding how they worked or what purpose they served, made my Java classes in University difficult for some time.

I'm not sure what point I'm making here, I just thought how it was neat looking back that my first language I learned I naturally branched into more FP-oriented programming.

Re:Why functional programming matters by mpweiher on Tuesday April 18, 2017 @09:48AM (#14138751)
> Why compose classes, abstract base classes, etc. when you can compose simple functions!

Because they allow you to compose higher level entities?

(Incidentally, one would generally compose objects).

"When programming a component, the right computation model for the component is the least expressive model that results in a natural program." -- Concepts Techniques and Models of Computer Programming

So when a less expressive model (such as FP) is sufficient for a "natural" program, definitely use that. And of course that has been the general recommendation. Switch to a more expressive model once this is no longer the case. In my experience, FP tends to be good for "computation", at least if performance isn't a primary concern. However, most of what "computers" (badly named) do today isn't computation, and modeling communication and storage over time tend to get awkward (though obviously possible).

Re:Why functional programming matters by louthy on Tuesday April 18, 2017 @10:20AM (#14138993)
> Because they allow you to compose higher level entities?

That isn't true. FP still uses data records, they're just not tightly coupled to the functionality like OO. Pure functions + immutable types is a more powerful programming paradigm than data and functionality encapsulation via classes and methods.

Also more advanced techniques like combinators can encode more complex and extensible patterns in a significantly more robust way than any OO class hierarchy (see 'parser combinators' for an example).

Re:Why functional programming matters by mpweiher on Tuesday April 18, 2017 @10:28AM (#14139067)
> (see 'parser combinators' for an example).

Lots of parser-combinator libraries in OO languages.

Re:Why functional programming matters by louthy on Tuesday April 18, 2017 @10:33AM (#14139105)
Your point being?
Re:Why functional programming matters by haskellandchill on Tuesday April 18, 2017 @10:14AM (#14138958)
> So when a less expressive model (such as FP)

You can express object models in FP so what you are saying is very confusing to me.

Re:Why functional programming matters by mpweiher on Tuesday April 18, 2017 @10:23AM (#14139023)
Models in "Concepts Techniques and Models of Computer Programming"

Note that they are talking about general models of computation, in particular including at least:

- Declarative sequential model (strict functional programming, deterministic logic programming, dataflow/logic variables, higher-order procedures). Component behavior is independent of rest of program.

- Declarative concurrent model (explicit threads, by-need/lazy computation, data-driven concurrency, demand-driven concurrency). Almost as simple as declarative sequential. Declarative model with exceptions: allows nondeterminism to be visible.

- Message-passing concurrent model (declarative plus ports/communication channels). Allows nondeterminism, and allows nondeterminism to be restricted to particular components.

- Stateful model (declarative model extended with explicit state). Allows components to keep history. Typical of sequential OO programming.

- Shared-state concurrent model (declarative extended with both explicit state and threads). Typical of concurrent OO programming.

- Relational model (declarative extended with search). Search space explored by testing choices until result is satisfactory. Encompasses Prolog-style logic programming.

- Constraint programming and still other models are discussed elsewhere in the book.

http://wiki.c2.com/?PrincipleOfLeastPower

Re:Why functional programming matters by novembermike on Tuesday April 18, 2017 @03:04PM (#14141852)
You do realize that the object model is just data bundled with functions, right? If I'm using Erlang I can pass in a map that has something like #{ data => [(data)], methods => [(functions)] }. The object style approach is orthogonal to FP.

EDIT: Just to be clear, I don't think this is a good idea. It's usually better to pass in one or more data structures and one or more first class functions separately. I'm just saying that it's not too different.

Re:Why functional programming matters by Const-me on Tuesday April 18, 2017 @11:21AM (#14139552)
> Why compose classes, abstract base classes, etc. when you can compose simple functions

For some kind of projects (video games, applied math, anything else that is sufficiently performance or latency sensitive), data structures are just as important as code. And they need to be composed, too.

For example, in C++ I can put small structures into couple megabyte-sized vectors, because memory controllers love sequential RAM access. Then I put these vectors in another vector, because address space might be fragmented and memory manager might not be able to give me continuous 1GB buffer, also to save CPU time + RAM bandwidth when growing my dataset to gigabytes. Then I wrap these vectors into another container that creates and maintains an index over the whole dataset using a hash map, because besides sequential access, other times I want to lookup my values by some key, and I want the lookups to run fast. And so on.

FP paradigm is just fine for composing functions. AFAIK, FP offers little for composing data structures. And those sophisticated specialized data structures are often the key for writing high-performance code.

Re:Why functional programming matters by patrickmn on Tuesday April 18, 2017 @11:29AM (#14139645)
There are libraries like https://hackage.haskell.org/package/repa that make some of these tasks much easier to do. (Write your program/algorithm in terms of these arrays and all operations on them are seamlessly parallelized.) And there's really no reason you can't wrap something by making a new data type that includes the original arrays and an index.. it's just not a class.

While it's worth mentioning that Haskell does allow you to get pretty low level, it nonetheless has a GC, and the code you end up writing often looks more like C than FP. Rust is a great alternative that combines a lot of the raw performance and control over memory of C/C++ and good stuff from FP (e.g. sum types/pattern matching.) (Or even better, use something like Haskell and FFI with Rust for performance-critical parts.)

Re:Why functional programming matters by Const-me on Tuesday April 18, 2017 @11:51AM (#14139844)
I never used Rust in commercial projects. But to my knowledge, data structures in Rust are not exceptionally good at composing, because the language lacks raw pointers.

In C++ I can add hashmap-based index to existing collection of values without duplicating the values, because I can only keep pointers in the map. I can add linked list-based LRU tracking to existing collection of values. I can use pointers to implement graph-based structures. While there’re workarounds in Rust, such as reference counted pointers, raw pointers in C and C++ are just faster.

Re:Why functional programming matters by kibwen on Tuesday April 18, 2017 @03:55PM (#14142302)
> the language lacks raw pointers.

This is incorrect, Rust has raw pointers. Those reference-counted pointers that you mention are all just standard library types implemented using raw pointers under the hood.

Re:Why functional programming matters by Const-me on Tuesday April 18, 2017 @05:12PM (#14142971)
I’m sure Rust smart pointers are implemented using traditional C pointers.

Regardless of how you call them, you still can’t use them to compose data structures into higher-level structures in Rust.

In C++ with raw pointers, I can combine a hashmap with an existing collection of values to speed up lookups, without duplicating values. I can combine hash map with linked list to create an efficient LRU cache, with a few lines of my own code.

C++ can do that because collections, std::unordered_map, std::list and the rest of them, expose raw pointers at their API boundaries. It’s possible to store these pointers in other collections, encapsulating one or more simple data structures into a higher-level specialized data structure, with the performance characteristics suitable for the job.

Re:Why functional programming matters by steveklabnik on Tuesday April 18, 2017 @07:54PM (#14144209)
A star-const T or star-mut T (wow I cannot figure out HN's formatting here) in Rust does absolutely everything a C pointer can. They're the same thing. You can do all the stuff you're talking about here. Exposing a safe interface does not also mean not exposing an unsafe one as well for these kinds of things.
Re:Why functional programming matters by Const-me on Tuesday April 18, 2017 @08:46PM (#14144484)
Technically, yes I can.

However, look at the Rust implementation of the LRU cache: https://github.com/contain-rs/linked-hash-map/blob/master/sr...

See how much code is there (more than 1k lines), and note most code is unsafe.

In C++, one would probably use list<pair<K,V>> for storage, together with unordered_map<K, list<pair<K,V>>::iterator> for indexing. And the implementation would be trivial, because there’s no need to re-implement a linked list, you only need to implement these get/set methods that update both collections at the same time.

In Rust however, they had to come up with their own implementation of linked list. The LinkedList from standard library doesn’t expose raw node pointers in the API, therefore it can’t be used for the job.

Re:Why functional programming matters by steveklabnik on Tuesday April 18, 2017 @09:30PM (#14144723)
Sure, but that's an oversight of the LinkedList API (which, honestly, was almost removed from std all-together, it's not exactly a shining beacon of API design) than some sort of inherent limitation of smart pointers, which seems to be what you're saying here.
Re:Why functional programming matters by Const-me on Tuesday April 18, 2017 @09:49PM (#14144843)
I don’t think that was an oversight.

I think rust safety model prevents rust containers from returning mutable pointers to the contained items. Especially pointers to item's implementation details, like nodes of that linked lists.

And without raw pointers to items, you can’t easily compose containers to make higher-level data structures from them.

Re:Why functional programming matters by steveklabnik on Tuesday April 18, 2017 @11:14PM (#14145182)
https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#met...

(That is, many data structure _do_ do this, and you _can_ do it. It is an oversight.)

Re:Why functional programming matters by jstimpfle on Tuesday April 18, 2017 @11:40AM (#14139762)
There is no reason why you couldn't "compose data structures" in FP. Lists are composed data structures, as are trees. And Haskell's type classes are in fact a superior way to build ADTs.

The difference is the mindset. FP makes it really easy to compose higher-level functions. But composing higher level functions typically means little control where the intermediate results are stored (which is what Game developers need).

You can absolutely write C++ style in Haskell by composing imperative functions (e.g. IO monad). The only problem I see is the syntax. There is no built-in syntax for indexing and assignment. Writing

    do
        v1 <- readArray a i
        v2 <- readArray a (i+1)
        writeArray a (i+2) (v1+v2+1)
instead of

    a[i+2] = a[i] + a[i+1] + 1;
gets old really quickly.
Re:Why functional programming matters by Const-me on Tuesday April 18, 2017 @12:13PM (#14140034)
> composing higher level functions typically means little control where the intermediate results are stored

Exactly.

I need my code to access sequential RAM addresses as much as possible, because performance.

And sometimes my RAM layout is fixed, because I’m directly sending large sequential blocks of RAM to GPU (e.g. on Windows, by calling ID3D11Device::CreateBuffer or ID3D11DeviceContext::UpdateSubresource), and GPU can only consume C-array of POD types with very specific alignment and padding requirements.

Re:Why functional programming matters by AnimalMuppet on Tuesday April 18, 2017 @12:40PM (#14140316)
Use the right tool for the job. If the job requires precise control of memory, FP is not the right tool. If the job requires precise control of sequence, FP not the right tool. (Yes, it's a tool that could be made to work, but you're fighting the tool rather than working with it.) If the job requires precise control of timing, lazy languages are the wrong tool.

This does not mean that there is anything wrong with FP or with lazy languages. They're just not the right tool for all purposes. When they're not the right tool, don't use them for that.

Re:Why functional programming matters by hota_mazi on Tuesday April 18, 2017 @10:14AM (#14138959)
> Why compose classes, abstract base classes, etc. when you can compose simple functions!

Why only do one while you can do both?

Modern languages have first class functions and support class polymorphism and parametricity, which is still a very powerful way to describe problems intuitively.

Re:Why functional programming matters by humanrebar on Tuesday April 18, 2017 @10:57AM (#14139316)
> Why only do one while you can do both?

Theoretically you can do both. Practically, few languages give you the tools you'd want to ensure functional purity.

C++ is a multi-paradigm language, for instance. But it doesn't have any concept of immutable data. The 'const' keyword exists but it only does a very shallow check for immutability (i.e., the pointer won't change but its data might). And even with a 'const', there are still huge backdoors (the 'mutable' keyword).

Point being, it's possible, but you'd be relying on convention in your design and care in your implementation to make it work.

Re:Why functional programming matters by mpfundstein on Tuesday April 18, 2017 @04:04PM (#14142372)
I think C++'s const is one of the strongest consts I know of. Java/C#'s const on the other hand...
Re:Why functional programming matters by hota_mazi on Tuesday April 18, 2017 @07:55PM (#14144213)
It's actually too strong and the designers of the language later had to introduce `const_cast` in order to relax it in certain circumstances.

In practice, Java's weaker `final` (immutable references) appears to be a reasonable middle ground.

Re:Why functional programming matters by morbidhawk on Tuesday April 18, 2017 @10:28AM (#14139062)
> OO abstractions and patterns OTOH, taught essentially in "elementary school" which possibly makes them seem easier to understand

What did I just read, you're joking right?

Re:Why functional programming matters by patrickmn on Tuesday April 18, 2017 @10:49AM (#14139246)
Not joking at all. Functional languages have a reputation for being hard to learn mainly because they aren't what most people learn initially (and switching paradigms is never easy, no matter which direction you're going.)

Disclaimer: The above is an opinion. Double-blind trials have not been performed!

Re:Why functional programming matters by morbidhawk on Tuesday April 18, 2017 @11:29AM (#14139644)
I agree that switching paradigms is not easy. The part that sounded like a joke and still sounds like a joke is downplaying the difficulty it is to learn OO abstractions and patterns. Even initially being taught them, does not mean you've really learned nor understood them well. When comparing it to something "elementary" I'd expect something simple like 13+4, not something as complicated as software design.
Re:Why functional programming matters by patrickmn on Tuesday April 18, 2017 @11:32AM (#14139669)
Nothing we do is easy for most people... that's why we're highly sought after.

What I meant was not that it's easy to do something, rather that it's something that often comes early, and is mandatory, in your journey of discovery. The concepts you learn early on, while not easy to fully grasp, stick, and make other paradigms seem alien.

Re:Why functional programming matters by dominotw on Tuesday April 18, 2017 @09:35AM (#14138662)
>Why compose classes, abstract base classes, etc. when you can compose simple functions!

What do you think of the recent rise of 'hybrid' languages like scala?

Re:Why functional programming matters by dagw on Tuesday April 18, 2017 @10:03AM (#14138868)
Personally I think they're great for development, but less great for learning. The advantage with something like Haskell is that it forces you do to things the 'right way' every single time and puts all the functional concepts right at the forefront. Once you've internalized the concepts then you can easily go onto other languages and bring those concepts with you.

While I haven't really written anything in Haskell since leaving school, learning Haskell has informed (and in my opinion improved) the way I program in every language more than basically anything else I've done.

Re:Why functional programming matters by js8 on Tuesday April 18, 2017 @09:55AM (#14138799)
My opinion is that it's a double-edged sword. It's like when someone recommends you to learn SQL and relational algebras, and you, coming from OOP world, say, oh, I can learn some ORM first, that will make it easier.

Personally, I found that diving directly into the language that represents a paradigm in the "pure" form (for FP I would recommend Haskell) works best for me. It makes it most obvious why things are done certain way.

Re:Why functional programming matters by patrickmn on Tuesday April 18, 2017 @10:57AM (#14139319)
A great way to get a taste of FP, but as others noted, not the best way to really learn FP (Haskellbook and SICP are great.)