162 points · by nonrecursive · 13y ago · 188 comments
However, consider a program where the main metaphor is controlling something. Logo, for example. Few people argue, I would think, that the traditional imperative styling there hurts and confuses things.
More extreme, consider stack based languages. These are strictly based on the current state of the program, yet my understanding is if you can fit your mind to that metaphor, it works very very well.
Or, my favorite category, cookbooks. Look at traditional baking directions: "Begin heating oven to XXX, mix dry ingredients in bowl, add butter, whip, ..." Doesn't get any more imperative than that, and yet people around the world often have great success replicating the desired results. (Granted, I often think that the difference in programming and teaching is that humans make an effort to understand what you were communicating, computers typically don't.)
Does this make sense?
Are you asking "Is it possible that purely functional programming is yet another paradigm that, like OOP, is fantastically useful but is still destined to be the square peg that is forced into too many round holes?"
If so, then yes, you're making sense. And yes, that's probably what will happen. However, as with OOP, the end result should be a net gain in knowledge and maturity for our very young field and yet another wonderful tool in our tool box.
Having said that, I think that with the "functional wave" comes a bit more understanding that this, too, may not be the perfect fit for every problem. Look at Clojure: they try hard to give you mutability in terms of abstractions that seem to encapsulate what it means for mutability to be a valuable thing.
In Haskell, monads are a great model of "what it means to be imperative". If you think of imperative programming as:
setup();
goLeft();
stop();
lookAround();
pickUp(ball);
turnAround();
Then monads try to make precise just what exactly those semi-colons are doing. To me, the fact that this is hard to understand is mainly the result of the language being the playground of mathematicians who have long since forgotten why such concepts are hard.In other words: there is a "meta paradigm" going on here and it's just starting to emerge. That meta-paradigm is to provide a language that gives you the abstractions to build the right abstractions to ultimately build the star-shaped peg that fits into the star-shaped hole.
So yes, if you're taking the long view then Clojure might be too opinionated for your tastes (and I have in fact opined on another thread today about what it would take to back slightly away from that lofty perch), then it sometimes can look like yet another oversold silver bullet language. But in the long term, we seem to be converging on something much healthier than the "stop using that paradigm and start using this one because it solves everything!" approach of the past.
Edit: So, monads help show what happens under the scenes for when you are writing imperatively, but they do little to illuminate when that style is beneficial. My contention is that this is up to the metaphors one has defined for their program.
For your monads example: one of the things I'm looking into is how to have the experts establish the monadic abstraction and have the system gain all of the benefit WITHOUT jRandomCoder at HugeCorp having to understand what a monad is... or even realize he's using one. Obviously Haskell falls short in that area.
This is coming from a big fan of functional programming and removing side effects.
I've read your post three times, carefully, and no, I actually can not extract a clear question from it. (I do not mean that in a mean way, just as feedback.) It seems to resolve to an observation that functional programming is not the only paradigm that has produced successfully-running programs, which is certainly true, but not terribly information-rich.
There are actually a lot of interesting possible directions you might be trying to go, but I'm not sure I want to try to guess them. (I will take one stab with: http://en.wikipedia.org/wiki/Effect_system )
I will observe that baking directions aren't a useful comparison; the difference between programming paradigms do not manifest until you have something that is a real size. Imperative is just fine for a single page program. Anything is just fine for a single page program; I have unashamedly written outright spaghetti code for single page programs.
I suppose some data analysis is done FP style somewhere, but is it comparable in complexity? (The data might be very complex, the algorithms too, but the code itself probably has much less branches, corner cases, ifs, and other PM-added mess).
Oh, and yes, I am aware of a web app written in lisp by pg, but I wonder if this experiment is really reproductible. Is this Viaweb code still maintained and running?
When the "world" from the point of a view of a program is an enormous drealocks-like hairball full of heterogeneity (which is the case for the code bases of most of the tools we use, Facebook, PowerPoint, etc.), I have hard time imagining that it can be modelled in a nice FP ether where well-behaved functions pass to each other all the data they need, and magically "reduce" it to a magically deterministic output.
Being able to do complex stuff with less mess sounds like a big win to me. Current users of FP in industry tend to be in the financial sector(though a quick check of haskell in industry shows several CAD users too).
Though I have to agree with you, I haven't seen a really convincing case study yet. For me at least it has wiggled its eyebrows and said look over there convincingly enough for me to take a look.
Yaron's talk: https://www.youtube.com/watch?v=hKcOkWzj0_s
Not sure how much I care for effect systems, just yet. Though, I think there is a high chance that is exactly what I want.
My main observation from such things as baking directions seems to be that functional (being a highly declarative style) is great for high level, but that you need a way to carefully logic about the lower level details as well.
To go with my baking example. The declarative would be, "Dinner should be enough pizza for X people..." This is great and all, especially if you are strictly at the management "high level" view of the task at hand. (Especially since this is likely to be part of a whole other set of declared outcomes. "Party room with X tables, etc...") However, one is not going to be able to actually get pizza for the crowd this way.
Now, one might say that at the lowest level one can have relatively "pure" functions such as "dice onions." It certainly seems this is where most blog posts spend there time. At the overall high level declarations and the low level functions. Often pointing out that one could even implement this with the "order from local store" keeping the high level meaningful and completely divorced from the lower level. My problem is most of these posts/papers completely lose track of the area where the actual steps to make the pizza, or arrange the party room, take place.
That is, at some level imperative works because it actually is easier to model in your mind. Why does nobody focus on identifying where that level of abstraction may be? Or do I just have a broken mind? :)
The real world doesn't have any pure functions. For one thing, pure functions are timeless; you can view their inputs and outputs as just existing. Of course in the real world it requires computation time to determine what the output is, but that is arguably a characteristic of our universe rather than the function. Trying to understand pure functional programming from a real-world perspective is to start at a grave cognitive disadvantage.
Which rolls nicely into...
"at some level imperative works because it actually is easier to model in your mind. Why does nobody focus on identifying where that level of abstraction may be?"
My opinion is that it certainly is easier to start with imperative, but the problem is that by bringing in all the complexities of the real world you are therefore inevitably building with complicated pieces, and the end result is complicated. Programming with pure functions and trying to isolate the real world is cognitively unnatural... but then again, so is trying to assemble a multi-million line program. That unnatural task is made easier by shearing away the real-world aspects of the function, and deliberately retreating to a much simpler components as much as possible.
My own attempt to elaborate on this theme: http://www.jerf.org/iri/post/2908 The braveclojure.com post grazed my point, but then pretty rapidly left it. My feeling is that people say things like "pure functions are easier to reason about", but still mentally leave that statement classified in "academic brain space" and fail to explore or explain why that's also a very important statement in "practical brain space". (If my mind is broken, it is in that I have refused to build the wall between those two that so many people seem to have.)
I think generally, a move to a declarative specification and operational constraints, plus some operational "here's how you do it" to fill in gaps, would be a good long-term move.
Seems to me that its the other way around; programs tend to have, at the highest-level, an inherently ordered set of interactions with external stateful interfaces, but at a lower level have logically pure computations on values derived from those interactions which control later interactions.
To go with my baking example. The declarative would be, "Dinner should be enough pizza for X people..." This is great and all, especially if you are strictly at the management "high level" view of the task at hand. (Especially since this is likely to be part of a whole other set of declared outcomes. "Party room with X tables, etc...") However, one is not going to be able to actually get pizza for the crowd this way.
Functional programming is very declarative, while still being totally specific. It is declarative in the sense that it describes what things are (as opposed to do this and that to get this thing), not in the sense that you give a list of constraints to a program and leave it to the program to make sense of those constraints - such as logic programming and linear programming. Descriptions like 'dinner should be enough pizza for X people' sounds like a constraint, like 'no more than 20 onions, at least 10 potatoes, potatoes are 0.5 currency per potato, you should have less cabbage than cod; maximize the nutritional value according to (linear function)'... Of course languages like Prolog has an understandable way of finding if a program satisfies all your constraints, but it is different from the execution model of an imperative language. Functional languages have the same execution model (well, from those that I've seen), only with a more functional style (and tools to do the functional style in a non-horrible looking way). The mathematical way of defining factorial is very declarative, yet it is also as specific as any imperative program you'd want to write to define factorial.
So I don't see what you mean about low/high level here.
Let's look at your example of baking. Indeed it seems like an imperative (physical) process. When we mix eggs and flour to form a batter we can't get the eggs and flour back! Indeed even cracking the eggs seems like destructive update to me. Think about why that is. We've performed a non-reversible transformation on our ingredients AND we can't go back in time! In this case time is implicit in our understanding.
Now consider trying to model baking mathematically. We want to build an equation that will tell us the state of our cake. This will be function - that is dependent on time - time is now explicit in our model. Now we can say at t0 our eggs are whole. At some time in the future t1 our eggs are cracked. This doesn't negate the fact at t0 the eggs are whole. We can't go back in time and update what the state of the eggs then - that makes no sense! So here we see that when time is an explicit parameter we have time symmetry. The equations don't care if time goes backwards or forwards.
And we can always do this. If you have some process that has a state that changes through time you can model that process with a static model that includes time as an explicit parameter. This means that our model is a higher dimensional look at the real thing. And our actual computation (or experiment or baking etc.) is a degenerate case of the more general model where the time parameter is actual time.
How does this relate to functional programming versus imperative programming. Well it is the difference between theory and experiment. But in this case we also have to deal with the fact that our program is computed (a physical process happening in time) and so we're using a physical computation which follows the rules of mathematics to model mathematical rules using a degenerate case of those rules. So if it seems like there's an abstraction leaking it's because it kinda is.
I like to think about it in this way because it highlights the very tight knit nature of physics and computation. Indeed a general theory of what it means to compute something could lead to a unified theory of physics and vice-versa.
I believe one can even see this in the OP. Some of those examples seem more complicated than the side-effecty, loopy code that they're replacing. Maybe it is all habit and my mind has been warped by years of exposure to side effects and loops. But what if those things are more "native" to programming than pure FP can easily allow, and we need a more physical model of computation?
I've often thought it would be interesting to try teaching programming as a kind of mechanics in which values are physical commodities that get moved around and modified—to see whether it would be more accessible to beginners that way. I also wonder what sort of programming languages one might come up with out of such a model. It would be an interesting experiment. One would use mathematical abstractions to reason about such a system, but would not think of the system itself as a mathematical one.
Oh come on. Is the fact that your processor emits slightly more heat from computing your pure functions, and once in a while a cosmic ray may shift a bit or two, really such a big hindrance? You sound like a die-hard purist, ironically. We might as well ditch the whole idea of applied mathematics since there is always going to be a mismatch between the real world and mathematics. Triangulate? You can't do that, because the degrees you measure isn't going to be measured to the 'infinitely' precise decimal point. The whole theory behind geometry is based on practically unatainable ideals; surely Plato would be turning in his grave if he knew that cartographers had been using geometry to make those (fairly inaccurate) maps. shudder
http://repository.readscheme.org/ftp/papers/ai-lab-pubs/AIM-...
I recommend reading the section on "Top Level vs Referential Transparency" after reading this article. It argues that the trade-offs for absolute transparency require the programmer to define the entire world ahead of time. This trade-off is not acceptable by the authors of the paper for reasons elucidated in earlier sections and in SICP and so they demonstrate a version of EVAL whose environment allows for forward-references to top-level forms which we know is useful to writing dynamically compiled programs and decoupled modules.
Every pure-FP language implementation has to make trade-offs with impure, mutable state and data. Haskell had to add the IO monad. Clojure has Var and Ref. Engineering isn't a discipline of absolutes.
http://this-plt-life.tumblr.com/post/44462204757/simon-peyto...
Thank you very much for this link! I should have known to search for work by these authors. I can only dream of a world where I could have found their works more prominent in something like infoq.
After living with a chef for a couple of years, I came to believe that recipes would be much more effective if less imperative and more focussed on exposing the contribution and relative importance of each ingredient/process for the final result. In cooking there is much variation on the inputs: I want to know if the lemon juice is there for taste or acidity so I can tell if I have a bad lemon and for what I can replace it.
It's like GPS navigation: the step by step instructions will often lead you off track. Let me see final destination on the map.
Now, a question that can be a bit of a hybrid is "why does this recipe make good tasting biscuits?" Starts with a limited scope and provides ingredient by ingredient level answers.
You had plenty of biscuits before, you know how you like them, and if you have experience baking them you know what can go wrong. So for biscuits the recipe model is fine. But for that lobster bisque soufflé you just picked off Joel Robuchon's cookbook? Not so much.
There are lots of posts on blogs, newsgroups, etc. about the aesthetic value of having one's code be math-like, but the working programmer doesn't necessarily care about that. That programmer probably does care about avoiding spooky action at a distance. Conforming to a "traditional math is [beautiful|divine|the true Dao]" ideology does not matter to that programmer as much as knowing what data a function depends on or affects.
My question is essentially have there been any approachable explorations of this topic? In my case, at least, preferably not starting from the perspective of category theory. :)
Yes, functional programming is analogous to cleaning your kitchen. You heard it here first, folks.
Of course, I think this is the main appeal of functional in today's world. We have so much computing resources that it often does seem we have unlimited memory and such. Essentially we move from cooking area to cooking area such that someone can clean up after us, and we only carry with us the items we are interested in.
Clean is a purely functional language with linear typing.
The main is that a destructive functions can call a non-destructive functions freely but a non-destructive operation, say "find best egg" should not have any destructive effects whereas "beat egg" can call "find best egg freely".
I know SQL separates destructive and non-destructive operations very clearly and it also allows the user to back out of some destructive action sequences if all the conditions aren't satisfied. This makes what to do when you don't have butter more easier solved.
Ultimately, I always fall back on programs not having a good concept of "consuming" or otherwise changing a variable. This is clearly doable, and elsewise it was referenced as linear typing (new to me).
contents = open(&ramen);
add_into( &pot, waterfactory() );
add_into( &pot, contents );
add_heat( &pot );
sleep( RAMENCOOKTIME );
tasty_ramen = open(&pot); type Recipe = Food -> Food
serve . fry . addPan kale . addPan (dice onions) :: RecipeI wouldn't use the recipe metaphor except to explain what a computer does in less than 60 seconds to someone afraid of electronics.
That is, the recipe for a single dish could be seen as a subroutine in the entire process pool for preparing a meal. Considered this way, what is the largest dining establishment you have seen? What is a menu, but a declarative listing of the strategies that an establishment can use to satisfy a customer's desire for dinner?
More directly, all of the metaphors of programming have almost direct analogies into the real world. "Worker" threads. "Queues" of "tasks."
As I've said elsewhere, I don't think I'm being particularly grand here. Just find it curious that, though we commonly have recipes and other directions that are mixes of declarative and imperative, the current trend in programming is to be purely declarative/functional. I wish I understood why that was.
Ever read a recipe designed for concurrency and/or parallelism? Functional idioms are becoming in vogue at the same time as people are meeting walls when it comes to single threaded applications.
I think a lot of this comes from the terrible division of "layers" that we have introduced in most common metaphors. Often we have to go through gymnastics to get all "mutations" back to a base layer where we can view them as "events" and then have pure functions that operate on these events.
Consider, the common division of "Storage, Logic, Display" that we try and hammer out in some form or fashion. It becomes all too often that one can not come up with a good way of describing these systems where events only propagate along a single direction in these layers. As such, we often find small silos of "storage" in the logic and display area. (Similarly, we have a small silo of "logic" in both storage and display, quite often.) Coming up with a mechanism where there is a single "storage" location for an entire application often introduces complicated logic.
Carmack had an interesting take on this idea for games programming, where the current logic "state" would be held immutable such that all calculations were only allowed to work on the current state. Kept those calculations easier, but introduced a new layer of effort to make that possible. Now, I think his argument was that this layer of effort could be seen as almost a constant factor that has shrunk in cost compared to the scaling cost of the number of actors involved in a modern system.
In other words if our current position in an array is 2, what we need to access the next position is the value 3. Creating a variable int i=2; and then mutating it i++; introduces the possibility of side effects. This not to say that at an abstraction layer below our programming language a register won't get incremented, only that our brains don't need to worry about the mechanisms most of the time if we use a functional language.
There's nothing magical about functional programming - it is no more than syntactic sugar to help programmers control the state of computing devices.
Foreach is a higher level abstraction that makes reasoning about our code easier. The bits still change.
In the same way that objects in Java are just syntactic sugar for encapsulating state. In the same way that a compiler is just the machine that takes a language of the syntactic sugar of language A to the actual language A.
> Foreach is a higher level abstraction that makes reasoning about our code easier. The bits still change.
So how do you write a Foreach loop from a regular for-loop in your typical imperative language? How do you compose that Foreach loop to make even higher level abstractions like map, filter and fold/reduce?
Halp!
One example of a way to structure a functional program is categorising functions according to whether they are a "source" a "filter" or a "sink", (terms stolen from circuit design). The source being your inputs (not pure), filters doing some transformation on the input, over time (pure) and handing off to a sink that causes some side effect (not pure).
In the "real world" You've probably made a lot of simple programs that mostly follow this structure if you've used unix pipes.
If you go along with this, you find that once you start making more sophisticated programs, you need some kind of "memory" so you can progress. Strictly speaking, memory, as we typically use it in imperative languages, is a kind of side effect. In the model above, though, you can make a special kind of "source" which is something like a feedback loop- a source that contains the output of the previous iteration of the program- or some sub portion of the program. Then maintaining a memory becomes a process of continually taking some input, transforming it, creating an output, and then using that output as an input again. (what you might call recursion)
Why would you do this? Because each part of a program like this is self contained, and its ability to do damage to some distant part of a program is extremely limited. It becomes much easier to reason about such a program. When you find a bug (and these are still possible) you can trace the origin from output to source, or source to output. There is no possibility of some phantom distant subroutine screwing up the dataflow.
And this kind of structure is very useful for games, interactive multimedia programs, and other such graphical interactive program.
A commonly cited "real world" example is xmonad. What I find more insightful is this article on replicating pacman in a functional language. http://prog21.dadgum.com/23.html
For a database example, here is the chapter from Real World Haskell about databases (a bit old but still relevant):
http://book.realworldhaskell.org/read/using-databases.html
And here is some example code:
do
conn <- connectSqlite3 "test1.db"
stmt <- prepare conn "INSERT INTO test VALUES (?, ?)"
execute stmt [toSql 1, toSql "one"]
execute stmt [toSql 2, toSql "two"]
execute stmt [toSql 3, toSql "three"]
execute stmt [toSql 4, SqlNull]
commit conn
disconnect conn
As you can see, it looks very similar to how you would write it in a regular imperative language. The main difference is that since they database operations are IO operations then they need to be in the special do-notation block and cannot be mixed with regular code.As for the question of wanting to mix pure and impure code that much I don't think it actually comes up that much. First of all, I find that I don't often find myself with an impure function that I want to add a side effect in the middle seamlessly - firstly, side-effecting stuff tend to be side-effecting from the beggining and secondly if I do want to turn a pure function into an impure one then forcing me to change the interface helps make sure that I am not breaking any code that used to work because it assumed it was working with pure code. Additionally, Haskell is really good at abstracting code so its not that hard to take a big chunk of logic and split it into a pure and an impure part. Finally, converting code from pure to impure is not that bad - sure, you need to change the syntax a bit but the type checker helps you find all the places that need to change and also helps you check all the code that calles the method you changed so you can be sure that you aren't breaking those.
side effecting operations in the IO monad so you can't run them in the middle of any function and instead must run them inside a special "do-notation block" like I did.
You can have impure code call both other impure code and pure functions and all you can't do is call impure functions from inside pure functions. Sure, its a bit annoying if you ever have to convert a pure function to an impure one (you need to change some of the syntax and all the places that call tha tfunction need to start treating it as impure) but its not that bad: first of all the type checker tells you all the spots where you need to update your code and secondly, Haskell is super good at abstracting code so its not hard to take a big chunk of code with some side effects in the middle and split it into a pure and an impure part.
> to academic program
Its a little pet peeve of mine but it seems that nowadays "academic" doesn't have a real meaning and just tends to refer to whatever people don't like. :)
connectSqlite3 "test1.db" >>= \ conn ->
prepare conn "INSERT INTO test VALUES (?, ?)" >>= \ stmt ->
>> execute stmt [toSql 1, toSql "one"]
>> execute stmt [toSql 2, toSql "two"]
>> execute stmt [toSql 3, toSql "three"]
>> execute stmt [toSql 4, SqlNull]
>> commit conn
>> disconnect conn
and it's "just" a bunch of nested lambdas with no "do" in sight. What's different from "regular" code is that those lambdas 1) return IO actions, and 2) are strung together with monadic bind (>>=) to build one big IO action.To be sure, in this case the do version is much easier to read (that's why "do notation" exists). It can be used with any monad, though - nothing ties it particularly to IO.
bar (foo x) --pure Haskell
vs foo x >>= bar --monadic Haskell
vs bar(foo(x)) -- in C you write both cases like this.By itself, this function is useless, but "interact" is a function with signature "(String -> String) -> IO ()" which means that it turns our "unwords . map upcase . words" into an interaction with the environment. There are whole debate here as to how interact is actually still pure, but for the purposes of this argument, interact is an impure effect.
The net program however is very simple: "interact (unwords . map upcase . words)". The pure part is decomposed into many other pure pieces, each with simple, small contracts and independent testability. The impure part also has a simple contract which is described in terms of pure computation.
Another great example is some of the streaming libraries available in Haskell today. Pipes for instance will let you compose a pipeline of pure and impure computations and have them work together nicely.
"fibsPipe >-> Pipes.take 20 >-> Pipes.print"
The first two segments are pure, but have empty "placeholder" slots for impure effects (identity monadic layers). These get merged seamlessly with the "Pipes.print" segment which has impure effects. All together, you get an infinite producer "fibsPipe" producing an impure effect "Pipes.print" while having its resource utilization and termination controlled by another pure computation "Pipes.take 20" which is actually maintaining its own implicit state (the current count of numbers it's let through).
But then you can decompose each piece and understand it on its own in a pure or simple impure fashion.
Now this is not to say that my keyboard is purely functional. The shift key creates state. But that state is isolated and short lived to the point where we can treat it as functional across two key combinations. It is the caps lock key which creates an unpredictable state - I do not know what output I will get without checking its status - the problem with state might be illustrated by the results of hitting capslock when I meant to hit tab while typing a program.
FP has mutable state.
People keep saying it doesn't because it's the first chance they've had to play with a keyboard that doesn't have a caps lock and they've realized that the number of times they accidentally TYPED A WHOLE PARAGRAPH IN UPCAPS has gone to zero and that tiny mental burden of tracking the state of the keyboard has vanished.
Removing mutable state improves trust.
It's no different than reading from a file - the state is out in the world and to be useful, a functional program must deal with it.
But note that the key difference is that the programmer does not create the state - it comes from the data. Probably also worth noting that the keyboard is used as an illustrative analogy not as example code.
I suppose the important point here is it's not possible for something going wrong with your monitor or speakers to suddenly remap your keyboard without warning.
As others have noted, there's really no such thing as a "purely functional program" unless all you're looking for is turning your CPU into a space heater. That said, there's a very real sense in which the parts of your program that ARE pure are much safer and easier to reason about.
The best way to visualize this is that you can theoretically turn an impure function into a pure one, watch:
void printAGreeting(string greeting)
{
IO.printLn(greeting);
}
That's impure. The string goes into a black hole and does nothing from the program's perspective, but changes the state of the world from everyone else's perspective (it probably makes pixels change on a display somewhere).So how do you make that function pure? Like this:
TheEntireUniverse printGreeting(string greeting, TheEntireUniverse u)
{
return u.makeSomeAtomsMoveAroundBobsConsole(greeting);
}
This function takes not only the string greeting, but everything else in the universe. You, me, everyone who's ever lived, bob's console, everything. It performs the same function by returning a new universe with everything the same except for the atoms moved to caused the greeting to appear on Bob's console.Obviously we can't do this, but (in Haskell, say) the IO monad is a context in which we understand that anything done inside of it has the affect of changing the "real world".
If you pretend that you really had to do the whole "universe dragging" thing around for anything in the universe that WASN'T part of your program (we're assuming it itself is in some black hole somewhere to avoid paradoxes and such), then you would darn well make sure you kept this pain-in-the-ass operation as "thin" as possible. Why? Well, you're lazy!
When you look at things that way, there's an analogy to writing stuff on bare metal hardware. You know you're going to have to write some assembly language (or maybe even direct machine code if you don't have an assembler). What you want is to get to the nice cozy world of C as soon as possible, so what you're going to do is use assembly to code only the smallest surface area you need so that writing in C makes sense, and everything else that doesn't need to be in assembly for performance sake you do in C.
So it is in a purely functional language. The idea is to "get out of IO land" as fast as possible. To use a DB as an example, you'd like to live in a world where your little view of the DB could be expressed in purely functional terms (writing functions that result in a modified version of that view) and only at the VERY LAST MINUTE would you send that DB view to an IO function that actually sent the view down the wire to the DB.
The same goes for files, sockets, gamepad IO, you name it.
And you'd be surprised how little you need to actually interact with the world between getting your data and pushing out state changes. A game, for example, can do a WHOLE LOT OF STUFF between reading the input state and writing graphics commands.
But the frameworks are lacking. The only web framework available got dissolved, and I don't have the energy to wire everything myself in a new language and paradigm that I don't even fully understand).
I have a strong feeling that once you understand either Haskell or Clojure, it will be a breeze to learn other.
My point was to get framework for functional programming that deals with a lot of I/O and side-effects and see docs for real-life examples of usage.
Rather, turned from a framework into a library. I only recently started with Clojure and found Luminus pretty easy to pick up. It just generates a simple scaffolding project which cherry-picks some good libraries into a project.clj file and gives you a basic "Hello world" web page to get started. Primarily it uses lib-noir on top of Compojure, so pretty much anything that was in Noir, you get here (I guess, I never used Noir directly). Luminus has a pretty good tutorial to cover basic notions of handlers, databases, etc.
No, it's not Rails or Django, and no it doesn't do anything you could do yourself from scratch pretty easily. It is, however, a nice starting point and may help you get over the "I have to wire everything together myself" hump.
Haskell is a very different language from Clojure and learning it will teach you different lessons. Haskell takes an uncompromising approach to purity which can sometimes be frustrating to manage. Haskell's type system is an incredible piece of work, one which some may dearly miss in other languages (Clojure's core.typed does help a lot in this regard).
But the frameworks are lacking.
From what I gather, the Clojure community (and the functional style and community in general) abhors frameworks. Small, reusable, composable libraries are the order of the day.
No, but it makes sense to learn haskell to understand functional programming, which is what you asked. Clojure's emphasis on purity is essentially useless without a type system to go with it. The type system is what separates the pure functions from the impure ones.
Plenty of that here: http://book.realworldhaskell.org/read/
Other batch processing programs works as well.
I've been writing javascript for years but functional programming didn't make sense until I realized:
1) It's essentially inverted callbacks. You can read and reason about your code by working from the inside out. The results of a function are passed up to the outside.
2) When you stop modifying variables and just pass them around, it becomes a lot easier to think about code in abstract ways. There are of course some situations where modifying a variable is needed, but it really feels icky and you think twice about doing it.
The problem I found trying to learn this stuff is that once you learn to think functional its hard to think like someone who doesn't get it. That makes it hard to translate concepts in ways that non-functional people can get easier. I'm keeping mental tabs on ideas as I understand them to hopefully help with this problem.
Also, macros. Clojure people love talking about them. They aren't explained well most of the time though.
Simplest explanation is that you can write a bunch of your own functions, even ones that will override native functions, i.e macros. Since clojure is a compiled language, at compile time all the source code gets read in and pre-processed. When the compiler reaches some code that was defined in a macro, it keeps rewriting that code until all the macros are processed and the code has been re-written. Then everything is compiled to bytecode for the jvm.
I agree with you that it's hard to remember not thinking functionally. I've only been doing it for maybe 3 years and it's hard to remember what it felt like when I was first trying to wrap my head around it.
With macro's, I think you mean to say your own special forms, not functions. They allow you to take in code as arguments, and determine when that code will get evaluated, letting you write things like "or" as macros, when it most languages they have to be implemented as built-in primitives (special forms).
Just reiterating the same definitions over and over to someone is somewhat like talking to someone in Farsi who grew up in rural China and only speaks a local dialect of Mandarin. Sometimes we have to point at things and make funny baby noises so people can ramp up their learning.
So when I said functions instead of forms, I did that because a) I don't understand the difference yet and b) that's not the point. I'm documenting how I, as someone new to both clojure and a stricter sense of functional programming, am starting to learn these concepts.
Eventually I'll grok the Matrix and all of this will seem hopelessly simpleminded. But for me right now, this is where I am on the road.
*Lighttable IDE: http://www.chris-granger.com/lighttable/
> It doesn't cause any side effects, e.g. it doesn't "change the external world" by changing external mutable objects or outputting to i/o.
These have little to do with one another. "sort :: [a] -> [a]" sorts a list, perhaps using quicksort. If you want to randomize the pivots, it's "sort :: [a] -> IO [a]", and everything in your program that sorts things has a different type, even though it produces the same value.
You need to walk through exactly what you are doing in your sum function, because it is not at all clear to the uninitiated where in the hell the "acc" variable comes from. Instead of explaining any of this part, which is perhaps the most difficult part for a non-FP person to grasp, you jumped straight to "by the way, use loop when there's a lot of numbers."
My coworker's comments when I sent him the link:
"Ok, I get it...... what's going on with the sum?..... whaaat?"
Thanks for doing what you're doing. I look forward to reading more of your work.