News for hackers. Stuff that matters.
Re:Trampolines in JavaScript by crazygringo on Friday September 06, 2013 @12:50PM (#6341338)
Genuine question, and this seems to be as good a place as any to ask it. I understand the concepts behind functional programming, and trying to implement them in JavaScript (recently read Functional JavaScript too).

But from my experience, functional programming is mainly useful for parallelization/distribution of computation, because it's essentially mathematical -- functional code tends to be harder to write, understand, and debug, but you do it when you need to be able to split up computation. Kind of like assembly is harder than C++, but you do it when you need 100% optimized computation in a section of your program.

But because there is obviously no multithreading in JavaScript, I've never found a compelling reason to use the FP paradigm in JavaScript. Can anyone enlighten me as to real-world situations where FP makes sense in JavaScript, either client- or server-side? Particularly in web-based projects, which is obviously what JS is for?

Re:Trampolines in JavaScript by lmkg on Friday September 06, 2013 @01:05PM (#6341427)
> because it's essentially mathematical -- functional code tends to be harder to write, understand, and debug

Many proponents of functional programming (including myself) believe exactly the opposite--that functional programs are easier to read and write, and tend towards being more modular which makes it simpler to test and debug.

This is mostly a product of experience and familiarity. My background is in mathematics, and I came to programming later. Many people come to functional program without as explicit of a math background as mine, but it's still mostly a matter of getting used to it.

Re:Trampolines in JavaScript by mattmanser on Friday September 06, 2013 @06:35PM (#6343053)
But they're obviously not.

We've now has 5-10 years of this new batch of FP languages and none of them have 'stuck', they've still not caught on.

It's not cause we're all dummies, it's because, generally speaking, for most problems FP sucks ass.

And that's the obviousness of it. If it were better, it really would have serious traction by now.

Instead people are integrating the best bits of FP into OOP languages. And at that at least they've been a wild success, it's made OOP languages a lot easier to program in. And will make Java easier to program in. Poor old Java programmers. Java 8 will be like a revelation...

Re:Trampolines in JavaScript by thaumasiotes on Saturday September 07, 2013 @02:38AM (#6344165)
> And that's the obviousness of it. If it were better, it really would have serious traction by now.

You're getting picked on here, and I'm going to do my best to add to the pile. From http://www.johndcook.com/blog/2008/03/25/innovation-ii/ --

""" In 1601, an English sea captain did a controlled experiment to test whether lemon juice could prevent scurvy. He had four ships, three control and one experimental. The experimental group got three teaspoons of lemon juice a day while the control group received none. No one in the experimental group developed scurvy while 110 out of 278 in the control group died of scurvy. Nevertheless, citrus juice was not fully adopted to prevent scurvy until 1865. """

So lemon juice cut the mortality of scurvy in sailors by forty percentage points (!), from 40% to 0% (!!). And a mere 260 years after this was demonstrated, it achieved "traction". Do you think you might be jumping the gun a little here? History would suggest that even if programming in FP style prevented 100% of bugs from occuring, the best you could say about its eventual adoption would be "it's a crapshoot".

Re:Trampolines in JavaScript by MaulingMonkey on Friday September 06, 2013 @10:13PM (#6343663)
But they're obviously not.

I'm going to challenge you right there. First, note that using aspects of functional programming doesn't immediately necessitate you do nothing but functional programming and use nothing but "functional" languages.

Consider a piece of poorly refactored C++ spaghetti you've been tasked with understanding. The same variables mean different things at different times... code assuming vectors have the appropriate length, then later normalizing them in place, and then later yet changing their direction... state being repeatedly accumulated and adjusted in different branches... how do you start cleaning this code up to understand it?

One of the first things in my hat is to start using a more functional style. I sprinkle around the const keyword on local variables like a madman, helping catch all code with side effects to local temporaries. Variables are split in twain, with vectors and their normalized versions being forced to have different labels. But therein lies the advantage: I no longer have to track "x means y except after z when it means y2", but can drastically simplify to "x means y" -- something I can usually encode in the variable name, easing pressure on my feeble memory. Moreover, since the constants stick around, I can paint a better picture of "before and after" much more quickly than through the pinhole of stepping (usually in one direction only) through more procedural code, simply by slapping a breakpoint at the end.

While I'm still not using nor desiring to use functional languages as my bread and butter, integrating functional styles into otherwise procedural code quite frequently helps save my time and sanity outright, even on those occasions when it feels stilted and unnatural compared to the procedural versions.

Re:Trampolines in JavaScript by fallous on Friday September 06, 2013 @11:21PM (#6343823)
I'm not entirely sure why this is getting downvoted so much other than possibly tone that offends the FP community (I'm sympathetic since the evergreen Perl is dying! stuff causes a twitch in me for down voting as well).

The biggest reason I have dismissed functional programming languages is that they appear to believe that all problems are pure (which in some cases are entirely appropriate to assume) but then have to exempt themselves from their own paradigms to deal with reality. What I mean is essentially what Kant declares with the categorical imperative, "wish it universal." FP paradigms always seem to have to exempt themselves from this in order to work with a lot of real-world problems.

Of course, I may just be old and not entirely grokking the real abstract ideas of functional programming.

Re:Trampolines in JavaScript by dragonwriter on Friday September 06, 2013 @06:40PM (#6343071)
> But they're obviously not.

They are obviously not for a substantial subset of the people who started programming with other-than-functional languages, which includes most current programmers. That's not the same as whether or not they are easier to read and write and debug and reason about in general.

> It's not cause we're all dummies, it's because, generally speaking, for most problems FP sucks ass.

Examples?

Re:Trampolines in JavaScript by mattmanser on Friday September 06, 2013 @06:45PM (#6343083)
Lisp used to be the lingua franca of universities. So, please, let's cite examples...

But seriously, state is inherent in most enterprise apps, which is to say, 95% of apps in existence.

Re:Trampolines in JavaScript by dragonwriter on Friday September 06, 2013 @07:03PM (#6343150)
> But seriously, state is inherent in most enterprise apps, which is to say, 95% of apps in existence.

That doesn't justify the claim that for most problems FP is poor; functional languages deal with mutable state, indeed, a big point of FP is that using it provides a way to cleanly divide pieces of code that deal with mutable state so that the presence of mutable state only complicates reasoning about those pieces of code that it inherently must complicate, rather than making the whole code base hard to reason about.

Re:Trampolines in JavaScript by tel on Friday September 06, 2013 @08:32PM (#6343413)
The lack of state in FP is a major myth. There's plenty of state, it just looks different than you're used to and, thanks to that, is far easier to reason about. It means that everyone who's first making the transition from imperative/OO to FP complains about it, but anyone who sticks around long enough to learn much anything besides "Hello World" learns quickly that there's really no problem.
Re:Trampolines in JavaScript by mprovost on Saturday September 07, 2013 @07:16AM (#6344718)
State is inherent but loops where recursion helps are sadly in scarce supply in enterprise apps (at least the ones that I've seen). Many (most?) apps are pushing data around, many times strings, often from a database. Lots of if statements, fewer whiles. Recursion can help with the kinds of problems that one encounters dealing with these types of programs, but it's not necessary and I would say probably doesn't even make things easier.
Re:Trampolines in JavaScript by theseoafs on Friday September 06, 2013 @08:04PM (#6343336)
And the overwhelming majority of those apps probably experienced a particularly nasty and expensive bug that was due to state (i.e. one that would have been very difficult or even impossible to replicate in a primarily functional environment).
Re:Trampolines in JavaScript by dustingetz on Friday September 06, 2013 @10:58PM (#6343766)
Except scala has achieved traction and clojure is hot on its tail
Re:Trampolines in JavaScript by jamesbritt on Friday September 06, 2013 @01:07PM (#6341438)
functional code tends to be harder to write, understand, and debug,

I've heard just the opposite. It's likely harder to write if you've being doing procedural code for a long time but the elimination of state, the referential integrity, makes things easier to reason about and easier to debug in the long run. The ability to compose larger methods from numerous small, state-free methods s a big win as well.

I've never found a compelling reason to use the FP paradigm in JavaScript.

My motivation to write more FP-oriented code is to reduce the number of WTF moments.

Re:Trampolines in JavaScript by crazygringo on Friday September 06, 2013 @01:14PM (#6341475)
Do you (or anyone) have any links to web-centric JavaScript programs written this way?

My confusion comes from the fact that I feel like most of the web-based stuff I deal with has to do with state -- the state of the DOM, the state of the database, the state of a connection, etc.

All the FP I read about always uses simple algorithmic examples (like factorials, Fibonnaci, etc.), and I've never been able to find a good example of a real-life webapp, say, that is written in a functional manner, that is a good example of how a program can be easier to write/maintain/debug/etc. Pointers?

Re:Trampolines in JavaScript by jdmichal on Friday September 06, 2013 @06:22PM (#6343000)
Here's an example that I'll put in here. Let's say you have an array of strings, and you want to create a UL element with each string in an LI. You can do this with a for loop just fine and everyone's happy:

    var ul = document.createElement("ul");
    for(var i = 0; i < strings.length; ++i) {
        var text = document.createTextNode(strings[i]);
        var li = document.createElement("li");
        li.appendChild(text);
        ul.appendChild(li);
    }
However, you can pretty handily turn this into a series of functional transformations:

    var ul = document.createElement("ul");
    strings.map(function (string) {
        return document.createTextNode(string);
    }).map(function (text) {
        var li = document.createElement("li");
        li.appendChild(text);
        return li;
    }).each(function (li) {
        ul.appendChild(li);
    });
The next step would be decomposing the functions into their own generic entities:

    function toTextNode(string) {
        return document.createTextNode(string);
    }

    function wrap(tag, child) {
        var wrapper = document.createElement(tag);
        wrapper.appendChild(child);
        return wrapper;
    }

    function append(parent, child) {
        parent.appendChild(child);
    }

    // Helper function to provide partial-application.
    // This is usually built into functional languages.
    function wrapIn(tag) {
        return function (child) {
            return wrap(tag, child);
        };
    }

    function appendTo(parent) {
        return function (child) {
            return append(parent, child);
        }
    }

    var ul = document.createElement("ul");
    strings.map(toTextNode).map(wrapIn("li")).each(appendTo(ul));
And now you have a bunch of general-purpose, easily-tested functions that you can apply in similar situations all over the place.
Re:Trampolines in JavaScript by cousin_it on Sunday September 08, 2013 @09:02AM (#6348577)
Hmm. In your perfect world, the code to solve that problem would look like this one-liner:

    strings.map(toTextNode).map(wrapIn("li")).each(appendTo(ul));
I'm not sure that's the most readable way to solve that problem. In my perfect world, the solution would be a template in a separate file:

    <template name="mytemplate"
              args="strings: array[string]"
      <ul>
        <li foreach="string in strings"
            content="string">
        </li>
      </ul>
    </template>
and in the code you'd do this:

    mytemplate.fill(strings);
Generating HTML is one of those tasks that really deserve a DSL ;-)

Also note that my solution doesn't really follow your pattern of composing several operations. The template loops over the array only once instead of three times. Maybe that's because it feels more natural to some people to nest several operations inside one loop, rather than pull out each operation as its own loop. I share that point of view as well, it feels weird to write a chunk of code differently depending on whether it's inside a loop or outside a loop. YMMV.

Of course the functional approach also supports putting all operations inside one loop. You could build up the composite operation by using a lambda (which would look similar to your initial imperative example), or using some function composition operators (which I wouldn't enjoy reading afterward).

Re:Trampolines in JavaScript by jdmichal on Monday September 09, 2013 @12:42PM (#6354476)
Understood, and templating is a good solution also. I specifically wrote what I did based on the original question, which I interpreted as "what does functional programming in a UI look like?" And I wanted to show the progression from a loop to inline lambdas to reusable and generic functions.
Re:Trampolines in JavaScript by jhart3333 on Tuesday September 10, 2013 @11:02PM (#6365251)
Thank you for your thoughtful and informative comment. This is what I read HN for.
Re:Trampolines in JavaScript by mattmanser on Friday September 06, 2013 @06:44PM (#6343080)
I generally don't like double posting in a thread but...

7 lines to 30 lines, with a never-ending call stack of despair if anything ever does go wrong.

That imo, is really shit code.

Re:Trampolines in JavaScript by BrandonM on Friday September 06, 2013 @07:57PM (#6343309)
But the 5 helper functions are all very reusable, making the code specific to this particular usage shrink from 7 lines to 2. With a handful more usages like this, they can have a huge decrease in code size.

And later on, seeing "map ... map ... each", it is immediately obvious that we are iterating over the entire array, producing new values, and then doing something with each of them. With the explicit for-loop, the unique logic is mixed in with boilerplate iteration code.

Of course, by now,

  for (var i = 0; i < strings.length; i++) {
      /* something with i */
  }
is a common pattern for us, and our brains skip right over it. Fundamentally, though, terms like "map" and "each" are much closer to the way we approach the problem. Do you really tell yourself, "OK, I want to start with i set to 0 and increment i to match each array index, then for each of those, I'll use i to extract the ith array element, then..."? There is a lot of extra baggage going on (WTF does i have to do with creating a bullet list?), with a lot of room to make a mistake; we've just trained ourselves to overlook it.

That's a huge benefit of functional programming IMO: replacing a bunch of repetitive, error-prone patterns with a higher-order function call.

On a side note, it's really unfriendly to call a comprehensive, helpful example "shit code." If you can relate your opinion in a slightly more respectful way, people will be more apt to listen to you.

Re:Trampolines in JavaScript by theseoafs on Friday September 06, 2013 @08:06PM (#6343344)
... not to mention that off-by-one errors and other confounding bugs are really common when you loop through the elements of an array manually. That's all but impossible with map, filter, and reduce.
Re:Trampolines in JavaScript by jdmichal on Friday September 06, 2013 @08:26PM (#6343396)
This is such a silly criticism, and is even sillier by the fact that I already answered it:

> And now you have a bunch of general-purpose, easily-tested functions that you can apply in similar situations all over the place.

EDIT: Not to mention that at least 10 of those lines could be removed with built-in currying and/or partial application, which any self-respecting functional language supports directly. JavaScript is not counted among these.

Re:Trampolines in JavaScript by tif on Friday September 06, 2013 @01:56PM (#6341706)
Sorry, I don't have any links to share off hand. But I do have some comments:

Of course we all have to deal with state, otherwise our programs are essentially useless.

As a casual FP practitioner, I try to make web-based design decisions that minimize the number of places where I handle state. The majority of the functions that I write just take values and return some referentially transparent transformation of their inputs.

So for me it's really more about black-boxing and forgetting (once it's thoroughly tested) about 90% of my code, thus hopefully limiting the scope of my state related wtf moments to the other 10%.

There was a time in my life where I thought that this sort of design was obvious and everybody was doing it. I've since learned, through lots of painful maintenance and debugging, that this is not at all the case :/

Re:Trampolines in JavaScript by dxbydt on Friday September 06, 2013 @02:56PM (#6342038)
> minimize the number of places where I handle state

The idea isn't to minimize places where you handle state. If you want to manage state, use a State monad. Here are some examples in Scala - http://stackoverflow.com/questions/7734756/scalaz-state-mona...

Re:Trampolines in JavaScript by tif on Friday September 06, 2013 @03:18PM (#6342129)
> use a State monad

Sure, I agree that that's the proper, academic, and purely functional way to handle state. Whether or not that introduces its own set of problems I'll leave as a thought exercise for the reader.

The key phrase in my comment was "casual FP practitioner." I'd only hoped to show OP a way to painlessly introduce some principles from the FP world , ones with, IMO, real and immediately obvious benefits, without cramming "monads and combinators and category theory oh my!" down his or her throat.

I tend to prefer simple, dumb, readable code to academic elegance, and I've found that treating data as immutable (whether it actually is or not under the covers) and preferring data transformation to state manipulation are two ways to get closer to that goal.

Re:Trampolines in JavaScript by cgag on Friday September 06, 2013 @03:20PM (#6342138)
The vast majority of your code probably isn't manipulating state, or doesn't need to be. You can have well defined boundaries where you're dealing with state. Read from the database, pass those values through a bunch of pure functions, then eventually rewrite to the database. You only have side effects when you intially read from and eventually write to the DB. Same goes for manipulating the DOM, and almost anything else.
Re:Trampolines in JavaScript by jshen on Friday September 06, 2013 @10:08PM (#6343654)
This book helped me answer the same question: https://leanpub.com/fp-oo

This talk is pretty good as well, but I already had a decent grasp on FP before watching, so it might not be as good before having such an understanding, http://vimeo.com/34522837

Re:Trampolines in JavaScript by theseoafs on Friday September 06, 2013 @01:01PM (#6341402)
That's a poor characterization of why functional code is "useful". People write functional code in languages that have no support for multithreading all the time. (Further, functional programming isn't often used for cases where optimization is super important -- imperative code can often yield faster solutions.)

Functional programming makes code simpler in a lot of situations. Statelessness is one of the big draws of the functional paradigm. If I'm debugging in a functional language and I find a variable has the wrong value, I can rule out stateful problems -- for example, I know I didn't accidentally reset the variable, and I know there's no code off in another function (or worse, another source file) that's messing with the state of the objects I'm managing. If you're debugging in a functional language, you can basically be certain that you got your algorithm wrong, which is helpful.

Re:Trampolines in JavaScript by c0mpute on Friday September 06, 2013 @01:28PM (#6341555)
As somebody who has written a lot of Java code before (read imperative) and now have had the opportunity to write more JS (which makes it a bit easier to write Functional) and also Scala, I think the process to "think" functionally takes time.

Sure, its easier to apply it to the mathematics domain and harder to something that many of us might think in OO. I guess it comes with taking small steps (as someone already said in a comment). Also, making conscious effort to keep questioning how functional our code is helps.

I saw this talk on functionatalks.org by Paul Chiusano (author of Functional programming in Scala) http://functionaltalks.org/2013/06/20/paul-chiusano-how-to-w...

If you see he repeatedly asks how can we make it more functional. I think that is kind of thinking we need to practice. Its hard after too much of imperative thinking I guess. One more thing I have heard is read SICP and forget OO for a bit :).

Re:Trampolines in JavaScript by sluukkonen on Friday September 06, 2013 @12:58PM (#6341386)
Small steps. Just using some simple functional constructs like `map` and `filter` will do wonders for your code. You don't have to start writing everything in a purely functional manner to benefit from it.
Re:Trampolines in JavaScript by crazygringo on Friday September 06, 2013 @01:04PM (#6341424)
Oh, for sure -- I use map/filter/reduce/etc. whenever I can when they result in cleaner/shorter code. They're great.

I'm asking more about things like tail-call recursion/trampolining, function decoration -- making the "architecture" of your program more functional, rather than just a few lines here or there.

Re:Trampolines in JavaScript by cgag on Friday September 06, 2013 @03:24PM (#6342160)
Recursion isn't really hard once you get used to it, and often leads to shorter/cleaner code. Map/filter/reduce are themselves very clearly expressed using recursion.
Re:Trampolines in JavaScript by mpyne on Friday September 06, 2013 @01:17PM (#6341495)
Indeed, I've started using many functional concepts in a Perl program I maintain.

Functional code isn't just good for concurrency, it also helps when trying to reason about lists and associative containers at a higher level.

Re:Trampolines in JavaScript by daxelrod on Saturday September 07, 2013 @01:21AM (#6344062)
For anyone interested in applying functional concepts to Perl, I highly recommend Mark Jason Dominus's Higher Order Perl[1], the full text of which is now available online for free.

It starts by teaching a reader moderately familiar with Perl functional concepts, and then it deep dives into these concepts and iteratively applies them to example programs to make them better.

[1]http://hop.perl.plover.com/