by steinuil · 4y ago · 0 comments
The author begins by replacing a language feature, the . operator, with a pipe() function. After that they swap out exceptions for Result, null/undefined for Maybe, Promise with Task, and the final code ends up becoming an obfuscated mess of wrapper functions and custom control flow for what you could write as:
fetch(urlForData)
.then(data => data.json())
.then((notifications) =>
notifications.map((notification) => ({
...notification,
readableDate: new Date(notification.date * 1000).toGMTString(),
message: notification.message.replace(/</g, '<'),
sender: `https://example.com/users/${notification.username}`,
source: `https://example.com/${notification.sourceType}/${notification.sourceId}`,
icon: `https://example.com/assets/icons/${notification.sourceType}-small.svg`,
})
)
.catch((err) => { console.log(err); return fallback });
...which is just as functional because doesn't involve any mutation and it doesn't require several pages of wrapper functions to set up, you can tell what it does at a glance without having to look up any other pieces of code, it's gonna run faster, and it uses standard control flow which you can easily debug it using the tools you use for any other JS code.This post has nothing to do with functional programming, this is a poor monad tutorial.
But the seemingly arising "Haskell religion" is at least as mislead as the OOP-religion that held mainstream in stranglehold for a long time.
Haskell's syntax isn't anything to imitate. It's hostile to IDE features, at least. Alone that should make it a no-go.
The next thing is that Haskell's features may make sense in the Haskell context, but they don't make any sense at all in almost any other language.
When you don't have strong types, no lazy evaluation by default, and it's not mandatory to use IO-wrappers, it makes not sense to mimic solutions that arose out necessities that are again results of constrains of Haskell's feature design. You need to do some things in Haskell the Haskell way because Haskell is the way it is. In a different language the chosen solutions are at best bonkers (even they may make sense for Haskell).
As always: It's a terrible idea to start doing something because "it's cool" and the "new hot shit", without actually understanding why exactly things are (or should be) done the way they are. The "Haskell religion" is by now imho already mostly only cargo cult… The more worrisome part is that it seems it attracts more and more acolytes. This will end up badly. It will likely kill the good ideas behind FP and only leave a hull of religious customs that the cult followers will insist on; exactly like it happened to OOP in the past.
That's my personal opinion, speaking as a big FP Scala fan.
I wanted to say the same but you were faster than me. The article reminded me a lot of the design patterns fad in the OOP world: that compulsion to make everything abstract and reusable even if there's no use for it yet. But hey, at some point it might be needed and then it would be great!
Of course there are some cases where you really want to be ahead of what might come , e.g. public library api's, but those are rare.
The overwhelming majority of problems do not fit OO, and using OOP on them makes a mess. Similarly, FP.
Can you elaborate on this? I haven't used Haskell in years but I recall enjoying some of its really cool IDE-friendly features, such as typed holes and the ability to press a key and have whatever is under my editor's cursor show me its type and another key to insert that inferred type into the document.
I have heard that more recent versions support nice record syntax using the '.' operator (but without whitespace, to differentiate it from composition). That's also very IDE friendly since type inference in the editor should be able to resolve the members of a data type that's been defined with record syntax.
When I hold some object I can easily discover the things I can do with that object—just by typing "." after the object reference.
In something like Haskell I need to know upfront what I may do with some "object". The IDE can't help me discover the methods I need. All it can do is to show me all available functions in scope. Most of this functions aren't what I'm looking for. But the IDE can't know that as it's missing the "context" in which I want to call my functions / methods.
And regarding records in Haskell: First of all you will get beaten when you use them (that's part of the religious movement and has nothing to do with comprehensible reasons). The other part is: Records are no substitute for objects. Not even close. Those are just quite primitive structs. (To learn how unpractical is it to try to build objects from structs without proper language support just ask someone who was forced to use C after coming from a more complete OO language).
Sorry, but this just isn't true. Hoogle <https://hoogle.haskell.org/> searches function by type, fuzzily: ask for functions whose first parameter is the type of the object-like thing, and you'll get just what you're looking for. And it's perfectly possible to run hoogle locally and integrate it with your editor.
Now, the tooling for a language like Java have had several centuries more of aggregate development work done on them compared to Haskell's tools, and if that polish is a difference-maker for you, that's fine! But it's not a fundamental limitation, and claiming it is is just fud.
>grug very like type systems make programming easier. for grug, type systems most value when grug hit dot on keyboard and list of things grug can do pop up magic. this 90% of value of type system or more to grug
>big brain type system shaman often say type correctness main point type system, but grug note some big brain type system shaman not often ship code. grug suppose code never shipped is correct, in some sense, but not really what grug mean when say correct
>grug say tool magic pop up of what can do and complete of code major most benefit of type system, correctness also good but not so nearly so much
I agree with you about C and Haskell's records, but I'm curious if you'd say the same about Rust's struct + impl system? Are there problems that can only be solved with real, Smalltalk-inspired objects, or can lightweight structs do the job if supported by enough syntactic sugar?
[1, 2, 3] &
^-- suggestion here
Unfortunately this wouldn't be very idiomatic in Haskell, maybe in Idris with |> this would make more sense?Haskell is great but it’s not for everybody. It really gets you thinking about software engineering in a different way.
I wrote Haskell full time for five years, with some of the best in the industry and I can tell you that there is no real religion. I will admit the language attracts ideologists, theorists and folks who like to pioneer (which I like), but everybody is just trying to make things work - these are patterns that solve problems and guidelines that avoid problems.
Now, it’s really hard to take the good parts of Haskell and bring them to a language like JavaScript and have it feel “natural” - especially to someone who isn’t a native Haskell writer! And especially a concept as reliant on higher kinded types as effects!
BTW: Haskell uses its IO wrapper also only for a very narrow set of effects.
One of my favorite examples: `head []` will result in a crash at runtime. IO won't safe you. (Besides that the whole "effect wrapping" story in Haskell is anyway shallow at best. There is nothing like "none observable effects" at all as every computation needs to happen in space-time, leaving observable traces therein; you can't define away "side channels" and call the result "pure"; that's mocking reality).
This is realllly unidiomatic in real world Haskell. Even removed from Elm and PureScript.
Idris maybe has better effect handling for your taste. Also see: Koka, Frank (mainly a paper)
We can't know whether the OOP religion is better, we also can't know if the Haskell religion is better, and we can't know whether NEITHER is better. (this is key, even the neutral point of view where both are "good" can't be proven).
We do have theories to determine algorithmic efficiency. Computational complexity allows us to quantify which algorithm is faster and better. But whether that algorithm was better implemented using FP concepts or OOP concepts, we don't know... we can't know.
A lot of people like you just pick a random religion. It may seem more reasonable and measured to pick the neutral ground. But this in itself is A Religion.
It's the "it's all apples and oranges approach" or the "FP and OOP are just different tools in a toolbox" approach.... but without any mathematical theory to quantify "better" there's no way we can really ever know. Rotten apples and rotten oranges ALSO exist in a world full of apples and oranges.
You can't see it but even on an intuitive level this "opinion" is really really biased. It seems reasonable when you have two options to choose from "OOP" and "FP", but what if you have more options? We have Declarative programming, Lisp style programming, assembly language programming, logic programming, reg-exp... Are we really to apply this philosophy to ALL possible styles of programming? Is every single thing in the universe truly apples and oranges or just a tool in a toolbox?
With this many options it's unlikely. Something must be bad, something must be good and many things are better then other things.
I am of the opinion that normal Procedural and imperative programming with functions is Superior to OOP for the majority of applications. I am not saying FP is better than imperative programming, I am saying OOP is a overall a bad tool even compared with normal programming. But I can't prove my opinion to be right, and you can't prove it to be wrong.
Without proof, all we can do is move in circles and argue endlessly. But, psychologically, people tend to fall for your argument because it's less extreme, it seemingly takes the "reasonable" mediator approach. But like I said even this approach is one form of an extreme and it is not reasonable at all.
I mean your evidence is just a bunch of qualitative factoids. An opponent to your opinion will come at you with another list of qualitative factoids. You mix all the factoids together and you have a bigger list of factoids with no definitive conclusion.
So you believe that the only way things can be compared is on quantitative measurements? Not with how they impress their users within whatever context they're in?
> I mean your evidence is just a bunch of qualitative factoids. An opponent to your opinion will come at you with another list of qualitative factoids. You mix all the factoids together and you have a bigger list of factoids with no definitive conclusion.
This is the process in which we gain knowledge in an uncertain world. I guess you could take the nihilistic stance and ignore it, but what's the use of arguing with nihilists?
No but I believe that quantitative measurements are the ONLY way to definitively verify certain things.
>This is the process in which we gain knowledge in an uncertain world. I guess you could take the nihilistic stance and ignore it, but what's the use of arguing with nihilists?
I'm not ignoring anything. I'm saying especially for programming, nobody knows anything. Which is actually better OOP or FP? Nobody knows. This isn't philosophy, there is no definitive proof for which is better.
The CPUs code runs on are imperative, with a lot of complexities and details hidden from programmers by magic the CPU does involving things like reordering and automatic parallelization.
However, none of the current languages are great at writing code that maps to how the CPU works. One can comment that functional programming does a better job of breaking up data dependencies, but imperative code can also do that just fine.
The problem with mapping paradigms to performance is that none of the paradigm purists care about performance, end of the day they care about theoretical purity.
CPUs don't care about paradigms, they care about keeping execution units busy and cache lined filled up.
It's not theoretical purity. It's more tech debt. How do I code things in a way where there's zero tech debt. Such that all code can be re-used anywhere at anytime.
We do have a theoretical method. It's the scientific method. Other than that, I'm largely of the same thinking. Also, confusing language implementation with overall design is a major source of confusion (eg Java vs OOP vs Erlang vs FP vs Haskell, etc)
How to measure "better" and how the data is interpreted, are the major stopping points to improving software language usability. There have been some attempts (re: Quorum). Classic OOP (inheritance, et al) is simpler to use than mixins for many projects. So now we have to worry about project size as another axis. Then we have to address the issue of median developer effort. What about memory? How do you weigh FP allocate-stack-as-a-for-loop vs reduced mutability? It's more complex than FP good OOP bad.
The point is: When things become a religion with cargo culting acolytes even the "best" approaches stop making sense.
That's completely independent of the concrete religion at hand.
I did not argue to "pick sides"!
In the end all the approaches are just tools. You need to wield them wisely for optimal results.
My point is:
Maybe one of these religions is right. Maybe something is the best. Maybe a side must be picked.
You didn't argue for better. You argued that everything is the same, that all things are good and nothing is bad and that every single thing in the programming universe is a tool in a toolbox.
I disagree. Violently.
The point is neither the culting acolytes OR people like you can prove it either way.
But calling people who don't share your opinion as "culting acolytes" is manipulative. The words have negative connotations and it's wrong. Extreme opinions in science and logic are often proven to be true, they are often validated. To assume that anyone without a neutral opinion is a cultist is very biased in itself.
Here's a good analogy: I believe the world is round. I'm an extremist. You on the other hand embrace all theories as tools in a toolbox. The world could be round or it could be flat, your the reasonable neutral arbiter taking neither the side of the flat-earther or round-earther.
The illusion now is more clear. All 3 sides are a form of bias, but clearly our science says only one of these sides is true, and this side is NOT the "neutral arbiter" side
This right here is the reason I don't like pure functional programming. Any engineer should be able to pick up your code and understand it pretty close to immediately. And with pure FP, even when they understand functional programming, they end up wasting valuable time tracking down what it is you're trying to do.
* I guess I need to edit to say I mean pure FP in a language not explicitly built for pure FP. The article is about implementing in JS, this is what I'm addressing.
Personally I find trying to write Haskell in an imperative language to make exactly as much sense as trying to write imperative code in Haskell. Same error, same reasons, same outcome.
There is a common story of a programmer who has journeyed like an itinerant martial artist looking for functional programming enlightenment but never finds it... Our industry is way too susceptible to snake oil stories like "If I wrote all my tests first my programs would never have any bugs" or "If I wrote my programs in Erlang they wouldn't have any bugs..."
There are certain tasks for which functional programming idioms are highly effective, other ones where you will twist your brain into knots and end up writing completely unmaintainable code.
This is just a special case of the more general principle, "Don't write X in Y". Don't write BASIC in C. Don't write C in Python. Don't write FP in imperative. Don't write imperative in FP. Don't think you've solved whatever problems you have with Y when you're forced to use it by writing X in Y. Writing X in Y inevitably leads to the worst of both worlds, not the best.
So a webdev should almost immediately pick up a mix of C++ and assembly?
No. There's a reason we specialize. That is not a good argument against functional programming.
Your argument (if I understand correctly) is that given some language (here javascript) that one ought not program in such a way that other people who use that language are incapable of understanding it. This example of FP involves a bunch of junk that makes javascript incomprehensible to javascriptors therefore it's bad.
Now, previous poster replies with "Hey not everyone understands c++ and assembly ..." and this does sort of sound like a strawman, however we can extract the core argument as "there exist things which you haven't seen before which you don't understand, but that doesn't make them bad" and that does not sound like a strawman. That sounds like a legit argument.
For example, perhaps there exists a library which performs some domain specific task using FFT, linear algebra, and distributed computing load balancer algorithms. All of it in javascript. An arbitrary javascript developer is probably not going to be able to understand what's going on. However, that wouldn't be a legit argument against FFT, linear algebra, or distributed computing load balancing algorithms.
Specializations exist. Pure FP in javascript might not be a great idea, but it possibly confusing someone who otherwise knows javascript doesn't feel like a real argument against it to me.
> So a webdev should almost immediately pick up a mix of C++ and assembly?
There's a reason assembly has been relegated to very specific & specialized use cases. I'd almost want to say the same about C++.
The best production code is very simple, very understandable.
And if you want to see an example for a language that is not like that, look at Scala and ZIO (www.zio.dev). It is a library for pure functional programming, but look at the examples - those abstractions you mention are not there. The library really aims at making concurrent/async programming easier by leveraging pure functional programming but without crazy category theory stuff.
That first example shows that the for syntax desugars to nested flatMap. Which is analogous to Haskell’s do notation, which desugars to nested bind.
The abstractions you said are not there, seem to actually be there in zio!
const doThing = async (url, fallback) => {
try {
const response = await fetch(url)
const notifications = await response.json()
return notifications.map((notification) => ({
...notification,
readableDate: new Date(notification.date * SECONDS).toGMTString(),
message: notification.message.replace(/</g, '<'),
sender: `https://example.com/users/${notification.username}`,
source: `https://example.com/${notification.sourceType}/${notification.sourceId}`,
icon: `https://example.com/assets/icons/${notification.sourceType}-small.svg`,
}))
} catch (error) {
console.log(error.message);
return fallback
}
}Wouldn't it block on the `await` calls, whereas the original code would instantly pass control back to the caller?
(Sorry if this question is odd. My JS is a little bit rusted).
I've overlooked the `async` on the first line… My fault. :-|
Async / await is just a code transformation that introduces Promise wrappers.
The code should be equivalent to the original. (I've just overlooked the top-level `async`…).
There are advantages to this approach like enabling different styles when appropriate.
There are disadvantages as well: you rely on the discipline of the programmers or tools to catch mistakes.
But there's nothing inherently wrong about thinking of programs in terms of FP ideas. There are other ways to think about programming than in terms of program counters, control flow statements, and procedures. It's not even idiomatic Javascript to write code that way!
JS is a more functional language than most people seem to think.
The tragic thing about TFA is that it's not an article but a chapter in a long series of posts and this is just one step along the way to showing how an FP style can manage the complexities of a non-trivially large JS code base.
• dot, `.`, syntax on objects vs. composition/pipe operators
• no autocurry
• no ADTs or basic pattern matching
• has null + undefined but no Maybe/Option (there is null coalescing and null chaining, but it’s easy to accidentally skip)
• const can still mutate the on the object, freeze incurs a massive performance cost
• no tail-call optimization outside Safari despite being in the ECMA2015 spec
• `class` keyword existed and private methods and values now, FP is pretty anti-encapsulation
• no immutable data structures in the stdlib
• no way to prevent side effects (/* __PURE__ */ in code generation is a hack)
Can you get benefits from avoiding state/mutation and choosing composition over inheritance? Sure, but it’s nothing like being in a language where these aren’t something you can do or the default, but the only way to write code and having the tool to express it.
... but some of those FP ideas are pretty neat and when used well can make code that is easier to maintain (for people who are familiar with the concepts).
If you need processing of streams of asynchronous dynamic ("hot") data it's the least-bad model I know, otherwise there are much better ways, especially now that many languages have async-await keywords or at least a Future/Promise type.
(Jafar is the author of Rx .Net, and even he couldn't explain it to the future author of RxJava :) )
As Ben Lesh often says, there are sadly a lot of misconceptions around Rxjs and the Observable type. The Observable type is a primitive so useful that it keeps getting reinvented over and over (React's useEffect is a weird React-only observable; a redux store is an observable); whereas Rx is a set of convenience functions to help with the use of the Observable type. If people are happy to use lodash, I can't understand what makes them so unhappy about Rx, which is like lodash, but for async collections.
I'm pushing to use react-query with the new app, I think people will get confused when it turns out hooking up the whole API will take hours.
I think the point being made was “each transform could be reusable across your codebase”, but I think for this example you really pay a high comprehensibility cost. And duplicating a few lines of code is often actually the right call, instead of coupling two unrelated bits of code that happen to be saying the same thing right now (but which will plausibly diverge in the future).
As a new Rustacean, I do really like Result and Option, but writing idiomatically in your language is really important too.