210 points · by adamnemecek · 10y ago · 165 comments
Andy, the same Andy mentioned in the article, wrote a blog post in 2014 with his perspective of what it's like to use Haskell in production, if you're interested. https://engineering.imvu.com/2014/03/24/what-its-like-to-use...
Question: what do you think of the thesis of pure4j [1] vis. frege [2]? Namely, are the advantages gained by switching to a haskell-like language far above those attained by simply forcing effects into a small part of the codebase?
Also. There is work underway to enable GHC to compile for the JVM.
Immutable types happen to be something that is familiar and comfortable to Java developers. I would therefore expect to meet a lot less resistance to "syntactic sugar and immutable classes" than "functional programming with pure functions" even if the end result is 80 percent the same.
I've been haskellin at a large Megacorp environment for the past 1.5 years, with lots of smaller freelance before that.
There's a lot of different value props one can make for different tools. One pragmatic case I make is that in Haskell land it's super easy and rewarding to to engage with upstream to resolve any problems I hit. One other angle that the imvu article and I think a lot of the comments over look is that using Haskell as a shared concrete specification / engineering design substrate for communicating actually makes it much much easier to collab with colleagues on pretty crazy projects. Even if the deployed system isn't ultimately written in Haskell.
That said, with the right colleagues, having the freedom / trust to choose tools that help you best deliver is always the ideal. :)
Best of luck!
You're right, though; pure4j offers an immediate and easily obtainable win, so it'd definitely be an easier pill to swallow. Thanks :)
I feel like some Java programmers would have almost as much culture shock with something like Haskell as some of the php programmers at IMVU apparently did.
Cheers!
But it introduces monads very similarly to how he did it: starting with Arrays, drawing parallels to Maybes, then introducing Control.Monad.State through an assignment before moving on to IO. This has helped me a lot in grasping the concept behind monads.
Before computers people modeled the real world using a Haskell-like pseudocode called "mathematics".
But then, sometimes you just want to iterate across a list of directories, read some files, and put some results in lists. Tail-recursion here feels dumb. Like, dammit, I'm the human and you're the computer, I know you can turn a sequence of instructions into a tail recursive loop for me, so don't make me think.
Haskell, due to its effectful / monadic vs. pure syntax distinction isn't terribly great here. Ideally I'd write all of my code in an "imperative style" all the time, but a row-typed effect inference system would determine which functions were pure, or in IO, or async, or in ST, or threw exceptions, etc. Koka [1] is an interesting language that explores some of these ideas.
I think the theory behind algebraic effects is a key step in making it easy to develop code with more stringent and customized safety properties than is available in languages like Rust.
[1]: http://www.idris-lang.org/ [2]: https://www.fstar-lang.org/
Yes, this would be a really nice approach (and it's not one that Haskell lovers would be upset by, BTW).
Some things are more intuitive as a list of things to do and changes to make.
(include the following stubs to compile):
let upload _ = async.Return()
let takePhoto i = async.Return [|0uy|]
// i stands for "photo i of N", a required parameter for our workflow
--- let runSequence n =
async {
let rec runSequenceRec (framesSoFar: byte[] list) =
async {
if framesSoFar.Length = n then
return List.rev framesSoFar
else
let! bytes = takePhoto framesSoFar.Length
do! upload bytes
return! runSequenceRec (bytes::framesSoFar)
}
return! runSequenceRec []
}
Nasty dual-level async calls, list reversal, recursion, if/else, an initializing []. A lot of visual junk that takes away from what the code is actually doing. I rewrote it imperatively to this: let runSequence' n =
async {
let frames = System.Collections.Generic.List<byte[]>()
for i = 0 to n do
let! bytes = takePhoto i
do! upload bytes
frames.Add bytes
return frames
}
Much cleaner, you can see exactly what's going on. I was fine with that, and that's where I left it until now.However reading some of the Haskell comments, I thought there might be something better. So I tried replicating Haskell's forM:
let forNAsync f n =
let rec runOnce (soFar: _ list) =
async {
if soFar.Length = n then
return List.rev soFar
else
let! result = f soFar.Length
return! runOnce (result::soFar)
}
async.ReturnFrom(runOnce [])
Okay, not pretty but it's a library function so we should never have to look at it again. With that in hand though, we can define: let runOneShot i =
async {
let! bytes = takePhoto i
do! upload bytes
return bytes
}
let runSequence'' = forNAsync runOneShot
This is terrific. Shorter and cleaner than the imperative method, preserves immutability throughout, and composes easily.If you were to try to compose `runOneShot` from the imperative method, you'd end up with this, because of your frames variable
let runSequence''' n =
async {
let frames = System.Collections.Generic.List<byte[]>()
for i = 0 to n do
let! bytes = runOneShot i
frames.Add bytes
return frames
}
Or if you wanted to try to rework the `runOneShot` to include the frames variable, it wouldn't be much easier: let runOneShot'''' i (frames: System.Collections.Generic.List<byte[]>) =
async {
let! bytes = takePhoto i
do! upload bytes
frames.Add bytes
}
let runSequence'''' n =
async {
let frames = System.Collections.Generic.List<byte[]>()
for i = 0 to n do
do! runOneShot'''' i frames
return frames
}
So, maybe things that seem imperative do work better functionally. You've just got to create some combinators that let you hook them up.Also, thanks for telling about Koka. It sounds very interesting!
In addition there is also machines/pipes/conduits, which all mix imperative I/O with declarative style code in an interesting and new way.
Immutable data may be a great idea. But is it the first that occurs to anyone? I have an MA in mathematics and the idea of mutable variables never seemed strange in the process of learning to program.
But even more, for a lot of people, even algebra isn't a natural way of thinking. What's natural is a series of instruction about how perform arithmetic. Learning what an abstract variable means is a hurdle for a lot of students.
The thing is that "natural", in this context, just means "what occurs to you first, all things being equal".
You may have a good and correct argument that learning Haskell is the right way to do things, that the costs of learning are more than exceed by the benefits.
But I don't think you can argue people into having functional approaches be the first thing that occurs to them.
I acknowledge that imperative programming is more analogous to real world tasks, but then as soon as you try to write your first program you run headlong into the fact that programming is nothing like other tasks you have done before. The tricks you have to learn to make imperative programming work are not really any easier than the tricks for other paradigms, and in fact you can mix and match from various paradigms to great effect (see: ruby).
You have no idea how desperately I wish more people understood that. I could swear that every introductory programming book produced in the last years was either written by someone who either completely forgot how hard this material was to originally master, or who was just some freak of nature who just intuitively grasped it.
Please, please, please, give your students a solid grounding in procedural (or even functional!) programming before teaching OOP. You can teach them about objects and how to use them, but please stop making people write entire classes before they have at minimum a month of coding exercises behind them! (Universities that teach CS101 in Java, I'm looking at you.)
Anyway, I strongly agree with you and reached for the upvote button, and ended up downvoting you instead. Stupid touchscreens.
There you go again, equating good and natural.
It seems like even functional decomposition can be unnatural for people even given the commonness of "one big loop" mega-functions as the solution created by a lot of contractors.
Certainly, the problems of mud ball and simple imperative programming styles is that they get harder as you go along.
Indeed, programming methodologies are more or less unnatural ways to program that allow programmers to be more productive and programs to scale in compensation for that unnaturalness.
Consider that mathematicians among the general public, pre-computers, were actually far more rare than functional programmers among programmers. Mathematics is also an unnatural construction. I grew having a great deal of difficulty with handwriting before computers appeared and I learned to love math shortcuts for the writing they saved me. But I also learned most people are more mentally lazy than physically lazy and on average would rather do more work than learn a new thing.
That said, people who connect this to software in a professional context are doing a disservice since hopefully software professionals have progressed in their intellectual development beyond their teens and are capable of abstract mathematical thought.
Not that this is some sort of indictment of imperative programming; it's a much better fit for a lot of different situations. But if you're trying to model something in abstract mathematics, pure or pure-ish function programming is likely to be a better solution. For example, look at the various proof assistants like Coq. Many of them are written in functional languages, and if you look at the code you can see why: the manipulation of formulas and proofs fits very well with an immutable, functional approach.
If you want more on the topic that's not from the hands-on perspective of an educator, you might have to go further back to Piaget's papers, but unfortunately I haven't had the opportunity to dive into these much.
And deep below, computers work under a model that's anything but functional (assembly language is basically a big mutable state machine).
There is value in understanding both imperative and functional programming and applying each of them wherever they are the best fit and there are some real world situations where sticking to immutability is a terrible choice (e.g. neural networks).
This is why we now live in a world where many programmers don't think there is a problem with running web servers on programming languages that slow down computation by orders of magnitude, in addition to being very cache and memory inefficient. We can scale! Yeah sure, use 50 servers where one could have done it. We would also use Saturn V to launch small individual LEO satellites, you know. Why not? It works!
Taking a functional approach is fine for a lot of tasks, and when you can do it without cryptic or inefficient code, you should do it. But when imperative is easier, use that instead.
> Well, you don't get to decide what people find natural, they do.
I am not contending that functional/declarative is a more natural way to think; I am saying that there is nothing inherently more natural about imperative programming. Since the latter comes from imitating the machine architecture up in the abstraction hierarchy, we should consider for a moment if this is really desirable.
> And deep below, computers work under a model that's anything but functional (assembly language is basically a big mutable state machine).
This is entirely irrelevant. Computers are highly stateful but the languages we design don't have to be stateful because of this. They have to meet the criterion of easily expressing the mental constructions we designate which I would definitely say is much better handled with statically typed functional programming languages.
> There is value in understanding both imperative and functional programming and applying each of them wherever they are the best fit...
We completely agree on this! Not all problems are best solved with functional languages (e.g., things actually involving the machine).
> there are some real world situations where sticking to immutability is a terrible choice (e.g. neural networks).
I don't see why immutability is a terrible choice for neural networks? Could you elaborate on this? It might be that almost all neural network implementations have been imperative so you have come to accept that as more normal.
It would be suicidal for these updates to be immutable (e.g. returning brand new neurons with the updated value instead of updating the neuron that's already in the graph).
Acutally, deep below a computer is a massive asynchronous electronic circuit. Your "big mutable state machine" is an abstraction, just like any other.
I also don't send a message to the cup of coffee to reduce the amount of liquid that is in it and pass it a PourIntoMouthStrategy object to act on.
This is certainly true. But there are also times when there is nothing natural about it at all. Consider this scenario:
I give you a cup of coffee. You set it on your desk to cool. Then when you go to take a sip, the cup is empty! You see, I gave you the same cup I was drinking from.
For the record I usually write functional code. Let me put another example instead of coffee. If I have a differential equation, "dx/dt=f(x,t)", I think of the solution as a function "x(t)", but if I try to solve it numerically or even try to reason about it I visualize how "x" changes with time. Is this the reason why numerical code is usually imperative? Maybe it's just because of performance but I really think that sometimes there is a cognitive burden trying to reason fully functionally (I can visualize the parabolic trajectory of a ball but I cannot visualize the 6-dimensional trajectory of an airplane doing a manouver without seeing it "change with time").
Tactic languages in theorem provers like Coq are stateful too: you have a proof state and you keep giving instructions for it to change. I wouldn't say that this is an unnatural way to think; for that subtask of the problem, we can view the proof as something with state without any problems.
"Mathematical modeling" sounds too sophisticated to be natural for humans. Let me illustrate what I meant; the kind of naturality I was talking about is this:
sorted(xs): a permutation xs' of xs such that, as we traverse xs' each element is greater than or equal to the previous one.
This is a perfectly fine sorting algorithm. It contains all the information we need to sort a list of comparable things, and it is very unlikely to contain an error; it is the _definition_ of sorting.
There are righteous performance concerns about this but ignoring all performance issues this is still more natural than listing out the steps needed to carry out the task of sorting. I don't think it is possible come up with a simpler recipe-like algorithm for this task.
There are recipe-like tasks in programming: ones that don't involve modeling the world; for those the functional paradigm would not be a good one. But these are rare if you are doing programming the right way.
In Haskell, this is evident in the complex and difficult to reason about graph-reduction engine that lays hidden in the runtime. Denotional semantics => Haskell Math yay. Operational Semantics => Haskell's downfall in real-world programmers.
http://research.microsoft.com/en-us/um/people/lamport/pubs/s...
I believe that the best way to get better programs is to teach programmers how to think better. Thinking is not the ability to manipulate language; it’s the ability to manipulate concepts. Computer science should be about concepts, not languages. But how does one teach concepts without getting distracted by the language in which those concepts are expressed? My answer is to use the same language as every other branch of science and engineering—namely, mathematics.
It makes me sad that some PFP enthusiasts enjoy the mathematical aspects of it -- as they should -- yet are unfamiliar with the more "classical" mathematical thinking. I think it's important to grasp the more precise mathematics first, and only then choose which approximations you'd make in the language of your choice. Otherwise you get what Lamport calls "Whorfian syndrome — the confusion of language with reality".
Dijkstra, in his "on the cruelty of really teaching computing science" makes a very similar point that people should learn how to reason about programs before learning to program.
This is why dependent types are a great framework to program in. If a program is worth writing, it should at least contain everything the programmer thinks about the program, including the reasoning of why it is the program he wants to write!
The interesting philosophical question is this: can programs be said to exist as concepts independent of the language in which they are coded (in which case the language is an artificial, useful construct) or not (in which case the concept is an artificial useful construct)?
Whatever your viewpoint, the "conceptual" state machine math is a lot simpler than the linguistic math offered by PFP.
Interesting, do you have any references for this? I thought that the primary reason for purity was to enable equational reasoning, but I have no sources for this. Also, AFAIK, there are no formal semantics for Haskell?
Don't know about a formal spec. I'm not a Haskell developer.
I think OO can be thought of as an extension of functional programming, except it has some fancy names and idioms (single responsibility principle, polymorphism, abstractions ... ), but in the end are incarnations of functions. For example, int String.length(){..} could be thought of as length(char[]):int function, and List.size() as length(List):int. Node Tree.next(DepthFirstStrategy) could be thought of as traverse(Tree, traversalFunction):Node. But because OO languages tend to be mutable, they lose the benefits of the FP world. However, because they are mutable, they tend to perform better in benchmarks. I think OOP implemented in an immutable language would be over-engineered FP, whereas OOP implemented in mutable language is just glorified imperative programming.
With my experience so far learning functional programming, I think it is a better tool: All the things you can do in OO world, you can also do in FP world, mostly better. When performance is of real concern, then those bits could be factored out into some imperative code - whether it's done in OOP or assembly, C is a matter of choice.
In other words, I think in the order of technology preferences, FP should be prioritized higher than others although there seems to be a steeper learning curve. I think FP is not getting the attention it deserves as a better tool.
Something to think about, since I'm thinking of swapping out some problematic C# code for F#. Pattern matching and a stronger, more expressive type system would be very nice. F# isn't as far off the reservation as Haskell, but I'm not sure how well throwing a monkey wrench, at the team will go.
I'm the CTO at my place of work, and our primary app is C#. I wanted to tame some of the excesses of the language, and started looking at Haskell - I knocked up a few small projects with it; got it talking to the C# app through RabbitMQ, all happy days. But a few months later I came back to the projects to find they had rotted because of cabal. Some projects I found it next to impossible to recover. That left a pretty sour taste, which was gutting because I loved the language.
Then I took a look at F#. It's not as impressive as Haskell as a language, but it really does sit in that sweet spot for 'fitting in' to a big project environment. I've found that creating satellite projects to our core app in F# has been the perfect way to go. It's moved the team into that mindset slowly without having to force the issue.
Can you elaborate on how that is laid out? I've identified some existing C# code in various of our current projects that could benefit from conversion to F#, but I'm not sure how the resulting projects should be structured.
Other projects are separate microservices that talk to our main app through my messaging framework [1]. It's an actor-model that I built a C# and F# API for, and they communicate via Redis. But tbh you can use anything you like: make it RESTful, use WebServices, RabbitMQ, etc. The great thing is you have access to the same libraries on both languages.
If you're thinking of refactoring existing projects then you could go the mechanical route of just converting classes like-for-like. But you miss out on some of the amazing type system benefits of F# if you do that.
What I tend to do is design all of the types first, as records or discriminated unions. A bit like if you were doing a DB related project you might spend some time designing the schema first, thinking about how the data should be laid out. With ADTs you can design the states of your application, whatever it is, and then you write the functions that transform those states in a referentially transparent way.
Then you book-end your lovely functional code with the IO.
This whole process is much simpler when you start with smaller services; so if you've found sections of your existing app that you want to break out, then that's perfect.
By the way, if you want some of the functional niceness in C# too, then check my library below. It was built with your situation in mind (because it's mine too). It also has some utility functions for F#/C# interop.
Although with C#'s the direction of travel (bringing in pattern matching, record types, etc.) I reckon C# and F# will end up more like Scala and OCaml, rather than Java and OCaml.
Nice to see open mindedness about languages for a change.
When I assess a programming language, one of the questions I ask myself is "How will this programming language help me write correct programs?" In more detail I want a language that helps with four goals related to the ability to produce programs that achieve their specifications:
(1) Partial correctness: the program doesn't give wrong answers
(2) Total correctness: the program does (1) and doesn't deadlock or get stuck in an infinite loop. It eventually produces a correct answer.
(3) The program does (2) within the desired performance bounds specified.
(4) The program does (3) while making efficient use of hardware.
Haskell definitely helps with (1). Reasoning about the partial correctness of Haskell programs is easier than it is with imperative programming languages. Total correctness is very hard, especially with multi-thread, multi-process, or multi processor programs, but I think that Haskell is helpful here as well.
The real problem is that Haskell makes (3) and (4) very difficult to understand. Some of this is that compilers for functional programming languages are magic, making it hard to reason about what they are doing. This is further aggravated by Haskell's non-strictness.
A discouraging look at Haskell: "Why Is Haskell Used So Little In The Industry"[1] and "Disadvantages of Purely Functional Programming"[2]
[1] http://flyingfrogblog.blogspot.co.uk/2010/05/why-is-haskell-...
[2] http://flyingfrogblog.blogspot.co.uk/2016/05/disadvantages-o...
Citing Credit Suisse and Standard Chartered is just
name-dropping big banks in the hope that it will deceive
people into thinking that these institutes are seriously
invested in Haskell. They are not.
Lol, Standard Chartered is hiring like 30 haskellers _this year_, and I'm pretty sure they were heavily invested in Haskell in 2010. That writer of that article has an axe to grind, and is twisting facts to suit it.* GHC’s support for safe concurrent programming is world-class
* Sound type safety led to refactoring being a breeze
* Fun, stretches the mind (for some people)
* Perfectly reliable unit tests.
* Concurrent batched IO.
* Abstractions for things like timeouts and running tasks on other threads while correctly bubbling failures.
* Fantastic support for safely encoding and decoding JSON.
* One of the best benchmarking tools I’ve ever used.
And the complaints amounted to:
* Devs have to think more about which String representation to use
* Devs have to think more about syntactical differences from the more familiar C-derived languages
* The team has to support more backend platforms, duplicate infrastructure
* Not a mainstream language (harder to learn, hire for, bus factor)
* “at this stage in my career I don’t want another programming language”
75% were for and 25% were against. Frankly the only complaints worthy of serious response were infrastructure duplication and hiring/skill development/bus factor. The rest are people just being close-minded and lazy.