4 ms·
I'm going to try and say this carefully, because I don't want to start a language war. Quite the opposite: I desperately want to change my views on programmin
by rprospero 14y ago
I'm going to try and say this carefully, because I don't want to start a language war. Quite the opposite: I desperately want to change my views on programming languages.
I've only recently started in Javascript, so I'm probably missing something, but I've been finding it a large step backward from Haskell when compared to Python. Specifically, list comprehensions and generators give Python a more functional feel. Meanwhile, the object system in Javascript has had me generating far more state than I ever would have in my Python code, while also requiring more manual type checking than I ever needed in Python.
I'm new to the language, so I'm sure that I'm missing something. I've read _Javascript: The Good Parts_ and it's helped me grow less frustrated, but I'd love to find out that this language is better than Python.
So, how do you write functional code in Javascript?
- kibwen 14y agoI can't answer your question, but if you're looking to emulate a functional style in Javascript I'd be remiss if I didn't point you toward Underscore.js: http://documentcloud.github.com/underscore/ http://documentcloud.github.com/underscore/
- rprospero 14y agoThanks! This is exactly the sort of thing that I suspected that I was missing.
- yummyfajitas 14y agoI wrote poorly, I wasn't meaning to imply js is haskell-like. It's scheme like. I write js using underscore and backbone, so while I have state, it's pretty well encapsulated. So I've got a few stateful backbone models. The inside of their methods tends to be primarily functional, followed by a stateful update: var intermediateResult1 = _.map( input, function (ss) {...}); var intermediateResult2 = _.map(input, function(ss) {...}); var intermediateResult3 = _.intersect(intermediateResult1, intermediateResult2); .... this.setState({ "my_attribute" : result }) My views are almost entirely functional - take a model as input, create some dom elements as output, and one side effect when updating the view. They may be just syntax, but multiline lambdas certainly help. And some of this is just library support. But all put together, it makes my js code far more functional than my python code.
- rprospero 14y agoThanks for the response. As I told Kibwen, the underscore library looks pretty neat. Also, my problems may have just been some brain damage on my part. I'd gathered that object hierarchies were the more idiomatic way to code javascript. I've been trying to write Javascript and then make it functional. I think I need to start writing functionally and just fit that into the Javascript. From what you've written, that looks pretty doable.
- deleted 14y ago[deleted]