307 points · by aranchelk · 2y ago · 237 comments
"It’s quite natural to program in Haskell by building a declarative model of your domain data, writing pure functions over that data, and interacting with the real world at the program’s boundaries. That’s my favorite way to work, Haskell or not."
Haskell can be intimidating, though, so I would recommend F# for most beginners. It supports OOP and doesn't require every single function to be pure, so the learning curve is less intense, but you end up absorbing the same lesson as above.
Modelling the business domain, reasoning and managing side effects, avoiding common imperative bugs, these are all valuable skills to develop.
F# is a great language to learn, and very approachable. Worst part about it is interacting with antiquated .NET API's. (I can't believe the state that .NET support for common serialization formats is still in...)
This is not true in my personal experience.
As has been famously said (paraphrased): Functional programming makes tough problems easy and easy problems tough.
In other words the value of functional programming depends on your domain.
That needs a qualifier: it can make easy problems tough if you're not familiar with how to solve them in a functional context.
A big part of that is because smart people have already solved the tough problems and made them available as language features or libraries.
And because of mutual recursion, that means that tough is easy (and easy tough). In other words, if we call the class of tough problems T and easy problems NT, we have T==NT, given FP.
I familiarized myself with fp to the point of writing scheme and haskell around 15 years ago. Read the classics, understood advanced typing, lambda calculus and so on. The best “fp” I’m using nowadays is closures, currying in the form of func.bind(this[, first]) and map/filter. Which all are absolutely learnable by the means of closures, which are useful but I can live without. Sometimes not having these makes you write effing code instead of fiddling with its forms for hours.
Still waiting for the returns from arcane fp-like code I produced earlier. Cannot recognize nor understand none of my projects in this style that I bothered to save in vcs. Imperative code reads like prose, I have some of it still in production since 2010.
These FP talks are disguised elitism imo (not necessarily bad faith). Beta reduction and monadic transformers sound so cool, but that’s it job-wise.
They may be disguised mathematics. People are into math because it is neat / elegant / cool. So they study it regardless of whether it has a practical use or not.
It might be a matter of taste, but I enjoy code built with functional abstractions that allow neat composable data flows and some caches loitering around. I find it also helps when adding UI. Sometimes performance could be better with mutation, but when I'm at that point I've already spent much more time tuning the thing with caches.
In practice, it's a pretty well-known phenomenon experienced by many skilled programmers that being forced into different styles by different languages results in learning things that you would only have learned very slowly if you had stuck only to your original language. To be concrete about the "very slowly", I'm talking time frames of your entire career, if not your entire life and beyond. It would be a long time programming in Java before you discover the concept of something like "pure functions" as a distinct sort of function, a desirable sort of function, and one that you might want organize your programming style around.
Of course, having heard of the concept already, we'd all like to fancy ourselves smart enough to figure it out in less than, say, three decades. But we're just lying to ourselves when we do that. Even the smartest of us is not as smart as all of us. You are not independently capable of rediscovering everything all the various programming communities have discovered over decades. If you want to know what even the smartest of us can do on their own without reference to decades of experience of others, you can look into the state of computer programming in more-or-less the 1980s, 90s if you're feeling generous. I think we've learned a lot since then, and the delta between the modern programmer and a 1980s programmer certainly isn't in their IQ or anything similar, it is in their increased collective community experience.
By getting out into systems that force us to learn different paradigms, and into communities that have learned how to use them, we draw on the experience of others and cover far more ground than we could ever have covered on our own, or in the context of a single language where we can settle into a local optima comfort zone. Jumping out of your original community is kind of an annealing process for our programming skills.
"The best “fp” I’m using nowadays is closures, currying in the form of func.bind(this[, first]) and map/filter."
That is really not the lesson about software design that FP teaches, and blindly carrying those principles into imperative programming is at times a quite negative value, as your experience bears out. FP has more to say about purity of functions, the utility of composition of small parts, the flexibility of composition with small parts, ways to wrap parts of the program that can't be handled that way, and providing an existence proof that despite what an imperative programmer might think it is in fact possible to program this way at a system architecture level. I actually agree 100% that anyone whose takeaway from FP is "we should use map everywhere because they're better than for loops and anyone who uses for loops is a Bad Programmer" missed the forest for the leaves, and I choose that modification of the standard metaphor carefully. I consider my programming style highly influenced by my time in functional programming land and you'd need to do a very careful search to find a "map" in my code. That's not what it's about. I'm not surprised when imperative code is messed up by translating that into it.
I love F#, the working with C# elements of the language drove me away.
Writing web applications and back-ends in F#, as far as I'm aware, is straightforward and a joy because of integration with the rest of ecosystem.
I still don't understand Haskell, but it did help me learn Rust when I decided to learn that. And I think I could explain what a monad is.
edit: It's a data structure that implements flat map. Hope this saves someone else a few years of their life.
It's not you. Haskell has very bad syntax. It's not hard to understand it, it you rewrite the same things in something saner. Haskell was developed by people who enjoy one-liners and don't really need to write practical programs.
Another aspect of Haskell is that it was written by people who were so misguided as to think that mathematical formulas are somehow superior to typical imperative languages, with meaningful variable names, predictable interpretations of sequences of instructions etc. They, instead, made it all bespoke. Every operation has its own syntax, variables are typically named as they would in math formulas (eg. X and X'). This makes no sense, and is, in fact, very harmful when writing real-world programs, but because, by and large, Haskell never raises to the task of writing real-world programs, it doesn't deter the adepts from using it.
And by the way x and x' are totally fine names for a value of a very generic type (or even a very specific type depending on the circumstances), as long as the types and the functions are decently named. I mean, how else would you call the arguments of
splitAt :: Eq a => a -> [a] -> [[a]]
?
There is no need for anything more complex than
splitAt x xs = ...
I was under the impression from the History of Haskell [0] that they were interested in unifying research into lazy evaluation of functional programming languages.
> This makes no sense, and is, in fact, very harmful when writing real-world programs,
Gosh, what am I doing with my life? I must have made up all those programs I wrote on my stream, the ones I use to maintain my website, and all the boring line-of-business code I write at work. /s
In all seriousness, Haskell has its warts, but being impractical isn't one of them. To some purists the committee has been overly pragmatic with the design of the language. As far as functional programming languages go it's pretty hairy. You have "pure" functions in the base libraries that can throw runtime exceptions when given the wrong values for their arguments (ie: the infamous head function). Bottom, a special kind of null value, is a member of every type. There exist functions to escape the type system entirely that are used with some frequency to make things work. The committee has gone back more than once to reshape the type-class hierarchy much to the chagrin of the community of maintainers who had to manually patch old code or risk having it not longer compile on new versions of the base libraries. These are all hairy, pragmatic trade-offs the language and ecosystem designers and maintainers have had to make... because people write software using this language to solve problems they have and they have to maintain these systems.
[0] https://www.microsoft.com/en-us/research/wp-content/uploads/...
(Of course in practice IO isn't implemented like this, because it would be too slow)
(But in every other language, like Javascript or Python, you can define IO as a data structure. Or even in Haskell itself, you can define for eg. a free monad that gets interpreted later, and it can be made to be just as good as IO itself, though typically people make it less powerful than IO)
However note that every other "computational" monad (like the list monad or the Cont monad) actually is a data structure, even though they describe effects just like IO does. This is because IO is the only possible exception to the "monads are data structures" thing in Haskell (if you don't subscribe to the above view), because Haskell doesn't let you define types that aren't data structures
The only issue with this point of view is that you now need to say what flatMap means for things that are not shaped like arrays. Eg. does it make intuitive sense to flatMap a tree? (A retort is that it must make sense, whatever you call this operation; and flattening a tree means to turn a tree of trees into an one-level tree)
As stringent as you need it to be (static vs. dynamic types vs. specs), as flexible as you want it to be.
First off, the compiler is single-pass. All your definitions have to be in order. This even extends to type hints - it can't use clues to the right to deduce the type of an expression on the left. This is supposedly for perf reasons, but the compiler can become extremely slow because the inference engine has to work so hard - slower than GHC for sure.
Speaking of slowness, Haskell is surprisingly fast. Idiomatic Haskell can be within 50% the perf of C, since its laziness and purity unlock powerful optimizations. F# is eager and the compiler doesn't do anything fancy. Perf often makes you reach for mutable state and imperative structure, which is disappointing.
The OOP paradigm feels bolted on. Should you use classes or modules? Pure functions or members? It depends, what mood are you in? Unfortunately only member functions support overloads, and overloads are useful for some SFINAE-type patterns with `inline` functions, so they get a bit overused.
`ref` struct support, which is vital for zero-copy and efficient immutable data, have very primitive support. even C# is ahead on this.
Very limited support for implicit conversions, no support for type classes and no function overloading leaves F# with nothing like a numeric tower you'd have in Lisp, and makes building something like Numpy clunky.
I use C# at work, and I love Haskell, so I really wanted to love F#. But it just doesn't get the love it needs from MS, and some design decisions aren't aging well - particularly as C# itself evolves in directions that are tricky for F#'s aging compiler to support.
They're often conflated because Haskell is pure and functional and probably the most talked about heavily functional language.
I certainly didn't know that impure functional languages like OCaml existed for ages.
It has exceptions
You can divide by zero
It has unsafe IO primitives
let x = <definition of x>
in ... x ... x ...
(i.e. defining a variable x and then using it some number of times) is equivalent to ... <definition of x> ... <definition of x> ...
Seen in the opposite direction (transforming the bottom code to the top code) this means that extracting repeated code is always a valid thing to do. It's not valid in most other languages, and certainly no mainstream ones.Exceptions aren't impure anyway.
In hindsight I think few would now regret not having added them in the first place.
To be tongue in cheek then it also has the side effect of heating the CPU.
Also interesting that when FP is mentioned, Hindley-Milner is implicitly understood to be part of FP too even though it doesn’t have to be. Clojure emphasizes immutability and FP but with dynamic typing and everything that comes with that.
The nuances of OOP in F# can be ignored by beginners, so I really wouldn’t let yourself be intimidated coming from Clojure.
I don’t know much about F#, but last time I used it most of its standard library was in C# and .NET, so F# code would interact with objects and classes a lot. AFAIK F# also doesn’t have functor modules, so even without the dependence on C# code, you still can’t avoid classes and objects like you can with OCaml (e.g. you can’t write a generic collection module like `List` or `Set` without functors, it would have to be a collection of a specific type or a class).
Is "emphasizes" just another word for second-class support?
C++ emphasizes the importance of memory safety.
I don't know what's your personal definition of "second-class support" but what it means is that it's explicitly supported by the language.
having never done F# or haskell, doesn't that start getting into the territory of languages that encourage functional programming like ruby or javascript (modern javascript)?
(F'2023 added a stronger form of "pure" and calls it "simple", but it didn't strengthen the places where a "pure" procedure should be required to be "simple", such as DO CONCURRENT, so being "simple" will be its own reward, if any compiler actually implements it. And a "simple" function's result value can still depend on a mutable pointer target.)
This is my experience after spending five years as a Haskell programmer and managing a Haskell team for several years and now moving back to the c++ world to play with AI.
I know lots of good c++ programmers working on cutting edge stuff, real experts in their field, but they sometimes still don't have a clear way to understand how to model data
That is my opinion. It's probably highly contentious.
In my experience FP-aligned people on non-FP projects tend to be more likely to overengineer, more prone to argue in favor of the Great Rewrite For No Reason Except Aesthetics, and more likely to abuse "lesser" programmers when they put up PRs. They suck as team players on teams that are not made of language nerds. I am not just talking about the one person here who I fired, this is a legit pattern I've noticed over at least a half dozen people.
Conversely, they are exactly the right people to deploy when you have really tough, self-contained problems to solve that you wouldn't trust the normal Java 9-5ers to tackle.
No matter how they do it, you can always rewrite their working code in a more maintainable language later once it's working, and make it integrate well with the rest of your stack. :D
Idris (2), PureScript, Elm, Unison, Roc, Lean (4), Koka, Flix (and some other I've forgotten about).
Haskell has very bad syntax (with extensive backing from Microsoft, iirc the guy who writes the compiler is a Microsoft's Research employee).
F# is a straight-up Microsoft's language.
It doesn't matter what other benefits it has. Just don't touch anything created by that company, and you will have one fewer regrets in your life.
But, if you still want a language from that category: SML or Erlang would be my pick.
There isn't an Overmind in MS that in a creepy voice tells you to spawn more overlords. Less than that, there doesn't need to be a written document that tells you to give money to MS or your data etc. There's just a general accepted understanding among the people who run that company that ends justify the means. And by "ends" they mean them and their investors getting rich.
If Haskell compiler could've been turned into a money-making machine, and it only required killing off half of Haskell programmer, MS would be working overtime on the plan to hide the bodies, but they'd never even consider the possibility of killing being bad... (metaphorically speaking, hopefully)
* There's no pattern or regularity to how infix / prefix / suffix operators are used which makes splitting program text into self-contained sub-programs virtually impossible if you don't know the exact behavior, including priority of each operator.
* There's a tradition of exceptionally bad names for variables, inherited from the realm of mathematical formulas. In mathematics, it's desirable to give variables names devoid of everyday meaning to emphasize the generic nature of the idea being expressed. This works in the context of very short formulas, but breaks entirely in the context of programs which are usually many orders of magnitude bigger than even the largest formula you've ever seen. There, having meaningful names is a life west.
* It's impossible to make a good debugger for Haskell because of the language being "lazy". Debuggers are essential tools that help programmers in understanding the behavior of their programs. Haskell programmers are forced to rely on their imagination when explaining to themselves how their program works.
* Excessive flexibility. For example, a Haskell programmer may decide to overload string literals (or any literals for that matter). This is orders of magnitude worse than eg. overloading operators in C++, which is criticizes for defying expectations of the reader.
One of these points would've been enough for me to make the experience of working with a language unpleasant. All of them combined is a lot more than unpleasant.
Also, on an aesthetic level, I think a lot of infix operators are kind of ugly. Examples include (<$>), ($), and (<*>). I think Haskell has too many infix operators. This is probably a result of allowing user-definable operators. I do like how you can turn functions into infix operators using backticks, though (e.g. "f x y" can be written as "x `f` y").
:-)
Immutable functional programming is basically what 80% of your Prolog code will look like. The benefit is that you'll be able to understand how everything works from end-to-end.
As I said, 80% of your code, or more, will look just like a functional programme.
There are some useful extensions like clpfd and asp but really if what you're doing is solving a constraint programming problem, you're much better of with OR-tools or MiniZinc.
Prolog is beautiful. I have practically no use for it. I've struggled to find something I can do better with Prolog than other tools, but I just love it aesthetically and that's enough for me sometimes.
So, I'd say that both languages lead people into very different programing styles.
[1] https://www.unison-lang.org/
[2] https://www.unison-lang.org/docs/fundamentals/abilities/for-...
I fear `ucm` a little. You mean I can't version my things with git? How do I... ehh, do anything? And how is the deployment story if one chooses not to use the Unison cloud?
I just like the very light syntax that it got from Haskell, but without the need for Monads and the "ugly" monad operators you need to juggle, replaced by abilities which IMHO are much more elegant.
They are focusing on writing cloud-services and apparently their offering is already pretty good, so if I ever need a clouse service I am tempted to use Unison (for anything not very critical, at least until I gain confidence in it): https://www.unison.cloud/our-approach/
And I love ucm and think it may be very close to what the future will look like (which is why I do agree it's ahead of our time). It's already possible to work with Unison but still have proper code review: https://www.unison-lang.org/docs/tooling/project-workflows/#...
Here's an example change: https://share.unison-lang.org/@unison/base/contributions/42/...
But currently, I believe you do need to pull the branch locally and then load diffs with ucm into your favourite diff tool to properly see what's been changed (which is not ideal , and I believe they are working on making this easier, we'll see).
> In this book, we will implement a simple static blog generator in Haskell, converting documents written in our own custom markup language to HTML.
> We will:
Implement a tiny HTML printer library
Define and parse our own custom markup language
Read files and glue things together
Add command line arguments parsing
Write tests and documentation
> In each chapter of the book, we will focus on a particular task we wish to achieve, and throughout the chapter, learn just enough Haskell to complete the task.The first half of the book is more geared towards a newbie to functional programming in general.
[1] https://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_...
In all seriousness, it’s not “text mode”, but one of the things that I felt really showed how cool Haskell and a friend could pure model could be a was Netwire and Functional Reactive Programming. It allowed me to design graphical applications the way I always wanted to instead of how they’re typically structured in imperative languages. There are lots of tutorials out there for making little games with it.
I was suggesting the Netwire library, an FRP library for Haskell.
Given that you want write code that sees "real world" use, and is used to handle data and events from the real world. To me, sometimes the line between optimized code and intellectual curiosity blurs.
1. It makes it easy to learn how to structure a program in a pure way, which is hard to do in languages that offers you a easy way out.
2. Since "everything" is pure, writing tests is easier.
3. You know for certain that if you discard the result of a function call, all the side-effects that it would normally trigger would be stopped as well.
4. A program where all side-effects are guaranteed to be pushed to the boundaries, is a program that's easy to reason about.
> a language which has adapted the best bits and pieces [...]
Languages that has adapted to best bits and pieces from X, Y, Z tend to be worse than a language specifically for X, Y and Z.
For instance, Java supports functional programming but functional programming languages are much better at it because they were designed for that specific paradigm. In the same vein, sure you can write pure programs in F#, but not as easily as in Haskell that was designed for doing just that.
> and is used to handle data and events from the real world
Pure code really only means (in practice) that side-effects are controlled, which is generally very helpful. It forces you to structure programs in a way which makes it easy to pinpoint where data is coming in, and where data is going out. It also makes for easier testing.
Being able to know, definetly, the answer to "will calling foo perform a network request" without having to read the source for foo is quite nice, especially when dealing with third-party code.
All this said, I probably wouldn't begin with Haskell. A language like Elm is much better suited for learning writing pure programs.
> 1. It makes it easy to learn how to structure a program in a pure way, which is hard to do in languages that offers you a easy way out.
When there's an escape hatch, you will reach for it at some point. It helps with getting things done, but you never end up really confronting the hard things when you have that, and the hard things are an important part of the learning/benefit.
Typical OCaml programs, when compared to similar C++ would be slower but use less memory.
F# and Scala are both OCaml in disuse. I don't know what you mean by "reasonable"... but, if the idea is "easy to reason about", then these two don't particularly stand out much.
Languages that are easy to reason about would be generally in the category where you need to do fewer translations before you get to the way the program is executed (i.e. bytecode adds an extra step, thus making a language harder to reason about). Also, languages with fewer primitives are easier to reason about, because the program text becomes more predictable.
In general, "functional" languages are harder to reason about when compared to imperative, because computers inherently don't work in the way the programs are modeled in "functional" languages, so there will be some necessary translation layer that transforms an FP program into a real computer program. There are people who believe that FP programs are easier to reason about due to the lack of side effects. In my experience, the lack of side effects doesn't come close to compensating the advantages of being able to map the program to what computer actually does.
All kinds of behind-the-scenes mechanisms in the language, s.a. garbage collector, make the reasoning harder too, in a sense. We pretend that GC makes reasoning easier by making a mental shortcut: we pretend that it doesn't matter when memory is freed. But, if you really want a full picture, GC adds a whole new layer of complexity when it comes to understanding a program.
Yet another aspect of reasoning is the ability of reasoner to act on their reasoning. I.e. the reasoning might be imperfect, but still allow to act (which is kind of the human condition, the way we are prepared to deal with the world). So, often, while imperative programs cannot be formally easily reasoned about, it's easy to informally reason about them to be efficient enough to act on that reasoning. "Functional" programs are usually the reverse: they are easier to reason about formally, but they are very unnatural to the way humans reason about everyday stuff, so, acting on them is harder for humans.
"Functional" languages tend to be more in the bytecode + GC + multiple translations camp. And, if forced to choose with these constrains, I'd say Erlang would be the easiest and the best designed language of all the "popular" ones. SML would be my pick if you need to get into the world of Haskell, but deciphering Haskell syntax brings you to the boil.
You start to see functions as self-contained things, as lego blocks. All the logic of the function is there in the function. It only works on values it receives as inputs (it can't read global variables). It only outputs its results (it doesn't assign them to some other global variable that you have to track down).
This makes your code modular. You can add a function in a chain of functions, if you want to perform an extra transformation. Or, you can replace a function with a different one, if you want to change something about the logic.
I wrote pure functions for a minute there but that's not the same, a function that only uses its inputs can modify an object while a pure function would have to return a new object. But, similarly, I bet that a lot more people know about pure functions than have any working knowledge of Haskell.
You have to follow both rules: the one about inputs and the one about outputs.
This is like a contract. If you enforce it throughout your program, you gain some guarantees about your program as a whole.
They'll experience no friction when using Haskell then. Haskell only refuses to compile when you declare "Oh yeah I know functions from other languages this is easy" but then do some mutation in your implementation.
> a language which has adapted the best bits and pieces from the functional programming paradigm?
Why write in a statically-typed language when dynamically-typed languages have adapted the best bits and pieces from statically-typed languages?
Unfortunately, dynamically-typed languages haven't adapted the best bit from statically-typed languages: that all types are enforced at compile-time!
Functional languages give you the same output for the same input, and almost-functional languages ... probably give you the same output for the same input?
main :: IO ()
main = do
coordinates <- getCoords
launch trajectory
where
trajectory = calcTrajectory coordinates
getCoords :: IO Coordinates
getCoords = -- TODO
launch :: Trajectory -> IO ()
launch = -- TODO
calcTrajectory :: Coordinates -> Trajectory
calcTrajectory = -- TODO
I can look at the types and be reasonably certain that calcTrajectory does no reads/writes to disk or the network or anything of that sort (the part after the last arrow isn't `IO something`), the only side effect is perhaps to heat up the CPU a bit.This also nudges you in the direction of an Functional Core, Imperative Shell architecture https://www.destroyallsoftware.com/screencasts/catalog/funct...
given that Haskell is lazy by default there's a million ways to shoot yourself in the foot through memory leaks and performance issues (which is not unlike the problems the IO type attempts to make explicit in that domain), so I never really understand this kind of thing. Purity doesn't say much about safety or semantics of your code. By that logic you might as well introduce a recursion type and now you're tagging everything that is recursive because you can easily kill your program with an unexpected input in a recursive function. To me this is just semantics you have to think through anyway, putting this into the type system just ends up creating more convoluted programs.
https://github.com/serprex/Fractaler/blob/master/Fractaler.h... fractal renderer I wrote in highschool, has mouse controls for zoom / selecting a variety of fractals
https://github.com/serprex/bfhs/blob/master/bf.hs brainfuck interpreter which mostly executes in pure context, returning stdout with whether program is done or should be reinvoked with character input. Brainfuck tape implemented as zipper
your program may exist in real world, but most of it doesn't care about much of the real world
I work full-time writing Haskell. Fintech stuff. No shiny research going on here.
I've written some libraries and programs on my stream in Haskell. One is a client library for Postgres' streaming logical replication protocol. I've written a couple of games. Working on learning how to do wave function collapse.
Believe it or not, functional programmers -- even ones writing Haskell -- often think about and deliver software for "real world," use.
Link? Story?
Real world? As opposed to what?
Is there any benefit to answering such polemical questions as if they are not rhetorical?
The only time I had contact with Haskell was in university and I did not see it appealing back then, nor now, nor have I ever seen a program that I use, written in it.
So learning a bit of pure Haskell might have been beneficial for me to become a better programmer, but I still fail to see it being more than that - a academic language. Useful for didactic purposes. Less to actually ship software.
The only mass market Haskell software that I know of is Pandoc. Others like Shellcheck and Postgrest are popular in their niche.
I am not sure that Haskell is faring worse that other programming languages in its level of popularity, like Julia, Clojure or Erlang.
Your mileage might vary, but I've heard advice from others to learn Haskell and "go off the deep-end" because of people citing similar reasons.
At my previous job, we used pure functional programming to ensure that custom programs only had access to certain side-effects (most importantly, not IO). This meant that it was trivial to run these custom programs in multiple environments, including various testing environments, and production.
I adore these sentences.:)When I read it,it feels like I met myself.
Are there any good resources you can share to learn this specific way of programming?