by ayberkt · 10y ago · 0 comments
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.
What I was talking about is: almost all lower-level abstractions are designed with the view of computer as a state machine. If we are solving a problem at an abstraction low enough to make us deal with this analogy, it is easier not to have a declarative layer in between.
machines/pipes/conduits are all very interesting and I was going to mention them too, but I still don't think they solve this problem in the way OP was referring to.
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.
But state transitions are pure! Deterministic state machines are nothing more than mathematical functions from one algorithm state to the next, and nondeterministic ones are binary relations! (see this for an overview: http://research.microsoft.com/en-us/um/people/lamport/pubs/s...) Those can then be mathematically manipulated, substituted and what-have-you elegantly and simply. This is how formal verification has been reasoning about programs since the seventies (early on the formalization was a bit more cumbersome, but the concept was as simple).
> For example, look at the various proof assistants like Coq.
For example, look at the specification language (and proof assistant) TLA+. It is far simpler than Coq, just as pure, and requires no more than highschool math.
Coq and other PFP formalizations are built on the core idea of denotational semantics, an approximation which at times only complicates the very simple math of computation, requiring exotic math like category theory.
> the manipulation of formulas and proofs fits very well with an immutable, functional approach.
The manipulation of formulas and proofs fits very well with the imperative approach, only no category theory is required, and core concepts such as simulation/trace-inclusion arise naturally without need for complex embeddings. "PFP math" is what arises after you've decided to use denotational semantics. The most important thing is not to confuse language -- for which PFP has an elegant albeit arcane mathematical formalization -- with the very simple mathematical concepts underlying computation.
PFP is an attempt to apply one specific mathematical formulation to programming languages (other similar, though perhaps less successful attempts are the various process calculi). But it is by no means the natural mathematics of computation. Conflating language with algorithms is a form of deconstructionism: an interesting philosophical concept, but by no means a simple one, and perhaps not the most appropriate one for a science. Short of that, we have the basic, simple core math, and on top of it languages, some espousing various mathematical formalizations, related to the core math in interesting ways, and some less mathematical. But the math of computation isn't created by the language!
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.
I don't think I am confusing anything, you are reacting exactly as I would expect from someone who does not get the point I'm making: we don't have to necessarily program with steps of instructions. If we have a good solver for our language, we can very efficiently execute definitions like my example. I agree that this presents the challenge of efficiently executing such high-level definitions, but this is irrelevant to my point.
> Mathematics sits at a level of abstraction unsuited to physical hardware.
Precisely what I am talking about. Mathematics sits at a level of abstraction convenient for humans not machines.
Have you ever programmed in Prolog? I strongly suggest you try it to get a feeling of why programs are not inherently lists of instructions and how computation can be viewed as deduction.
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.