
Functional Programming using JavaScript - openmaze
http://scott.sauyet.com/Javascript/Talk/2014/01/FuncProgTalk/
======
leeoniya
finally, a slide deck that uses `history.replaceState` instead of
`history.pushState`. no more having to hit "back" 90 times to exit the deck.
how the latter ever became a pattern is beyond me.

[EDIT] it probably became a pattern because of browsers that didnt implement
the history API, so all hashchange events were pushed onto the history stack.

~~~
9point6
To be honest, using replaceState for this doesn't seem to make sense to me. A
user would probably want to go backward and forward through this using browser
history navigation (for instance using the navigation buttons on their mouse).

If you're launching a link from a page you expected to come back to, surely
opening the link in a new tab would be the way to accomplish this?

~~~
leeoniya
personally, i've always used arrow keys, swipes, pgup/pgdn to nav between
slides. i _want_ a single-action "exit slide deck to previous page", and the
browser's back is the logical place for that to be, imho.

~~~
jmathai
I think the lines between a single page app and full page reloads needs to be
blurred. Most people won't know the difference and the back button needs to
behave consistently.

For that reason, I think that pushState here would make more sense. The state
of the page does, after all, change.

~~~
leeoniya
it's not a mental "context switch", though. i think the way android has the
back button implemented is very sensible.

------
lelf
For those you want to learn the functional programming I'd suggest to
immedeately commence looking at Ocaml/Haskell instead to see the real big
picture. Because it's of course adorable that you can write _map_ and
_compose_ in JS (it's 2014, it can do it everywhere), but FP = many more
serious things.

~~~
zackmorris
I've been wondering lately, if we skip performance as a consideration (for
example lazy evaluation), what is the difference between functional
programming and imperative programming without globals, pointers, mutable
variables or shared memory? In other words, would an imperative language
without side effects (that could do static code analysis) be any different in
practice than FP?

I'm very serious about this, because as far as I can tell, the next best
aspect of FP might be first class functions, but those are starting to be used
more in mainstream languages (at least the technique of applying
transformations on generic data rather than writing special classes everywhere
or using templates).

I'm beginning to feel that the real advantages of FP are being obfuscated by
unusual syntax. There should be no reason why we can't go from some of the FP
notations to the plain old algebra style (x=y) of C-style languages like
Javascript. With better references and immutable variables, we should be able
to split calculations up over several lines and have the compiler figure out
how to optimize it into basically FP code.

P.S. I do know lisp, so I'm asking for a rather more enlightened answer than
just to research it further.

~~~
tel
Pure FP is very different from imperative languages because it has no notion
of temporal order. You can (in truly pure FP) evaluate things in whatever
order you choose and stop as soon as you're satisfied. The language cannot
care at all [0].

That said, FP often involves the introduction of monads which restore
sequencing (along with many other beneficial effects). A monadic FP
computation is _very_ similar to a plain imperative computation... just with
all of the arbitrary details automatically selected to be coherent and
optimal.

You can even pretty easily embed OO in FP languages (though it gets a little
hairy sometimes) since as soon as you can simulate open recursion somehow you
can get late-binding as you like. See Oleg's O'Haskell papers for this kind of
nonsense.

[0] In this regard, even Haskell is impure since it allows for non-terminating
computation which can be seen as an impurity since you cannot expect to just
evaluate `let x = x in x` repeatedly and get anywhere meaningful. Other
languages like Coq, Agda, Idris are terminating (thus not Turing Complete) and
therefore truly pure.

~~~
zackmorris
Thank you, I hadn't considered that FP can evaluate in arbitrary order or
simultaneously. That makes sense, because if there are no dependencies between
code paths (so no side effects) then there's no reason they can't be executed
at the same time. They didn't mention that back in the Scheme course I took in
college, and I think something vitally important was lost on us (although in
fairness they did emphasize that the code was evaluated, not run
sequentially).

Seeing how monads reintroduce temporal dependence is also an astounding
insight, and I can't believe that I've never seen them described that way.
That means that the monad has more in common with, say, the mutex, than it
does with I/O. I've always tried to approach them with metaphors like sockets
and utterly failed to grok anything for more than a couple of days.

I'm thinking that if Haskell is an "impure" functional language, then I would
like to see a "pure" imperative language. I envision it as similar to Go but
multithreaded and basically every function in the language would be its own
process, communicating with sockets (so basically a shell with C-style
syntax). The overhead could be largely eliminated with a stackless context
switcher. It wouldn't be able to achieve the optimization of FP but it might
be more approachable to the mainstream and by extension maybe iterate faster
and lead to higher productivity. I’d like to see it take the place of
OpenCL/CUDA and SIMD because I find them tedious compared to more elegant
languages like MATLAB/Octave.

~~~
tel
I'd suggest taking a look at Coq if you want something more pure than Haskell.
I'll warn you that this comes with some degree of added sophistication! Coq is
not just a programming language but instead a proof system which can be used
to verify programs as _correct_ (not just unit tested) and then extract the
skeletal, underlying program as OCaml, Haskell, or Scheme code.

[http://adam.chlipala.net/cpdt/](http://adam.chlipala.net/cpdt/)

True purity actually doesn't look much like Go at all. Instead, it means that
every expression literally can be evaluated and replaced with its value in a
completely arbitrary order. This massively simplifies the meaning of a
language and opens it up to bear much more structure (such as that of a
mathematical proof).

------
sramsay
I'm a huge fan of lo-dash, but might switch to Ramda. Here's a rundown:

[http://bahmutov.calepin.co/lodash-to-ramda-
example.html](http://bahmutov.calepin.co/lodash-to-ramda-example.html)

------
idlewan
The author is misrepresenting imperative code [0]. Instead of the 42 lines of
code he thinks is imperative, but really is already functional-compatible,
this is what I would write:

    
    
        var getIncompleteTaskSummariesForMember_imperative = function(memberName) {
            return fetchData().then(function(data) {
                var tasks = data.tasks;
                var results = [];
                for (var i = 0; i < tasks.length; i++) {
                    var task = tasks[i];
                    if (task.member == memberName && !task.complete) {
                        results.push({
                          id: task.id,
                          dueDate: task.dueDate,
                          title: task.title,
                          priority: task.priority
                        })
                    }
                }
                results.sort(function(first, second) {
                    return first.dueDate - second.dueDate;
                });
                return results;
            });
        }
    
    

Still longer than the 10 lines of functional code, but a much more fair
comparison.

[0]:
[http://scott.sauyet.com/Javascript/Talk/2014/01/FuncProgTalk...](http://scott.sauyet.com/Javascript/Talk/2014/01/FuncProgTalk/#slide-123)

~~~
the_imp
I was bothered by the presented functional implementation; it seemed to use a
whole pile of library-specific functions to do the same things base JavaScript
already does, just expressed slightly differently.

This would be the code I'd write for the same task, pure JS assuming that
fetchData returns an ES6 Promise:

    
    
        var getIncompleteTaskSummariesForMember = function(memberName) {
            return fetchData().then(function(data) {
                return data.tasks
                    .filter(function(task) {
                        return (task.member == memberName && !task.complete); })
                    .map(function(task) {
                        return {
                          id: task.id,
                          dueDate: task.dueDate,
                          title: task.title,
                          priority: task.priority
                        }; })
                    .sort(function(first, second) {
                        return first.dueDate - second.dueDate; });
            }, function(reason) { console.log(reason); });
        };
    

Now, does that count as functional? I'm not sure I really care, but it's
certainly JavaScript-ish.

------
swah
There is also @fogus' book:
[http://shop.oreilly.com/product/0636920028857.do](http://shop.oreilly.com/product/0636920028857.do)

I haven't read it yet.

~~~
joshuacc
It's a fantastic book for getting your mind used to the functional way of
thinking.

I'd also recommend JavaScript Allonge on the same topic.
[https://leanpub.com/javascript-allonge](https://leanpub.com/javascript-
allonge)

~~~
CrossEye
For JS people wanting to learn FP, I'd recommend Allonge first. For FP people
wanting to see how they can use JS in and FP manner, Fogus' Functional
Javascript is a good book, and it's not a bad second book for the JS crowd.

~~~
derengel
I'm curious what you think about Clojurescript? leaving aside that it may be
harder for teams to move to Clojurescript than to improve their JS codebase.

The reason for the question is that Clojurescript supports all the FP idioms
of your slides more naturally and also has more FP features.

~~~
CrossEye
I've just started learning Clojure, and I haven't spent any time yet on
Clojurescript.

------
roneesh
This is a really nice presentation that introduces a lot of concepts well and
also helps a person conceptually understand how functional programming fits in
to the larger programming world.

Book mark it and share it.

~~~
pentlander
I agree, a lot of people tout how functional programming is easier to both
read and write, but this really puts things in perspective. I especially like
how he explains how the different standard functional functions work in very
simple terms and immediately shows the advantages of using them.

------
bodyloss
Intrestingly it seems that the functional version he proposed is much faster
than the OO version. [http://jsperf.com/oop-vs-ramda](http://jsperf.com/oop-
vs-ramda)

~~~
CrossEye
(Author of that talk (and co-author of Ramda) here. Your perf test only times
the parsing of the function -- not exactly fair.

~~~
derpface
Hey man. Great work.

------
seomis
I dislike these expositions on the "differences" between object-oriented and
functional programming. The two concepts are not directly commensurable, and
one can have objects with referentially transparent methods, to be used in a
declarative style.

~~~
rmrfrmrf
Agreed. Everything about this slideshow seemed like the author was _slightly_
off the mark about what functional programming is and why it's useful.

------
atrilumen
I believe this is the author of Ramda, yes?

I can't find the talk, anybody got a link?

(Ramda is pretty bad ass.)
[http://ramda.github.io/ramdocs/docs/](http://ramda.github.io/ramdocs/docs/)

~~~
CrossEye
There is no video for this. I gave the talk several times to small groups, but
never recorded it. Sorry. But you don't want to see my ugly mug, anyway.

~~~
belgianguy
Thanks for that! It was a nice introduction, I have a colleague who usually
made my eyes glaze over when he started about FP, but now that I have seen it
in an environment that I understand and use in my day to day job, a lot of
"a-ha" moments occurred in rapid succession. I also liked the humorous bits.
It's all pretty self-explanatory and well put, a little Googling will fill in
any gaps an interested pupil might face.

------
killtheliterate
I put together a similar talk last summer:
[http://thedrearlight.com/functional-js-
wut](http://thedrearlight.com/functional-js-wut) unfortunately, don't have the
vid either, but the slides might be complementary to the ones linked by the
OP.

\--edit It's formatted kinda weird, where both up/down and left/right arrows
navigate through the different sections.

~~~
CrossEye
Very nice talk! I've used that formatting too, and while it can be very useful
when running a presentation by yourself, it's not so nice for slides shared
with someone who doesn't know it.

------
bahmutov
Trying to ride the wave: I have written about functional programming in
javascript, see blog posts
[http://bahmutov.calepin.co/tag/functional.html](http://bahmutov.calepin.co/tag/functional.html)
\- Ramda is great!

~~~
CrossEye
I've read and commented on many of these posts (the latest one far too
frequently! :-) ). Excellent stuff.

------
inglor
His functional example in Bluebird and some ES6 (traceur) just becomes:

``` return fetchData().get("tasks").filter(x => x.member ===
memberName).filter(x => !x.complete).map(x => {x.id, x.dueDate, x.title,
x.priority}).call('sort'); ```

------
facorreia
Bravo for promoting functional programming and showing how it can be done in
JavaScript. One issue concerns me, though: using strings to reference
attributes. This makes static checking tools much less useful and can lead to
difficult to find errors due to refactoring and typos.

~~~
blablabla123
Promoting FP using SQL as an example for encoding business logic doesn't look
to me like a nice example...

~~~
CrossEye
The idea was just to show that, contrary to many people's expectations, OOP is
not the only widely used paradigm in business programming.

------
serve_yay
These slides are very difficult to read on a touch device.

~~~
CrossEye
I apologize. I really posted it on my site only as a convenience for myself,
not to be published. I never really considered anything but projection at the
time. Although I can view it on my fairly large phone, the experience is not
great.

------
ktg
See also fn.js (Functional JavaScript Library)|
[https://bitbucket.org/ktg/fn](https://bitbucket.org/ktg/fn)

------
debacle
I assume these slides are from a talk?

~~~
CrossEye
No video was recorded on the occasions I gave the talk. I'd apologize, but
actually, you should probably thank me. :-)

~~~
buzzdecafe
you missed a golden opportunity to rickroll hacker news readers

~~~
CrossEye
Hasn't that meme died yet? Well, I for one won't help keep it alive by
pointing to the recently discovered talk video found here:....

------
areski
Can we find the talk somewhere?

