Hacker News new | past | comments | ask | show | jobs | submit login

I think you're making this too abstract to be understood without having already seen the light, perhaps an example would help?



Okay, sure, let's look at it in Javascript.

The task? Take a list of numbers, and produce a list containing only the squares of those numbers--and only those squares falling between 10 and 50.

  var inList = [1,2,3,4,5,6,7,8,9,10];
  
  var non_fp = function ( myListOfNumbers ) {
  	var out = [];
  	var temp = [];
  	var i = 0;
  	var j = 0;
  
  	// square the numbers
  	for (i = 0; i < myListOfNumbers.length; i++) {
  		temp.push( myListOfNumbers[i] * myListOfNumbers[i] );
  	}
  
  	for (j = 0; j < temp.length; j++) {
  		if ( temp[j] > 10 && temp[j] < 100 ) {
  			out.push( temp[j] );
  		}
  	}
  
  	return out;
  }
  
  var fp = function ( myListOfNumbers ) {
  	return myListOfNumbers.map( function (x) { return x*x; } )
  			      .filter( function (x) { return (x > 10)  && (x< 100); });
  }
The first has no side effects.

The second version has no side effects, and wouldn't be possible without first-class functions, and to me is clearly the more functional answer.


Suggested minor change to the non_fp one:

  var inList = [1,2,3,4,5,6,7,8,9,10];
  
  var non_fp = function ( myListOfNumbers ) {
  	var out = [];
  
  	// square the numbers
  	for (var i = 0; i < myListOfNumbers.length; i++) {
  		var x = myListOfNumbers[i] * myListOfNumbers[i];
                if (x > 10 && x < 100) {
                        out.push( x );
                }
  	}
  
  	return out;
  }


That's a correct change--I chose the implementation that I did so that it was very obvious how the things remap to a "functional" approach. :)

You see the point I'm driving at, though?

(and thanks for prodding me into writing code to illustrate things better)


> You see the point I'm driving at, though?

Yes, absolutely. I thought you were right on the money with the words but I figured a bit of code would do wonders to hammer it down.

Erlang does an even better job I think:

  [X * X || X <- lists:seq(1,10), X * X > 10, X * X < 100].
Or:

  [Y || Y <- [X * X || X <- lists:seq(1,10)], Y > 10, Y < 100].
Slightly longer, but without that X * X repetition.


Yep. Erlang/Elixir is actually kind of a joy to work in for math stuff. Shoot me an email if you'd like to chat about that.


I'm slowly slogging my way through Project Euler in Erlang, it's my default way of learning anything new and so far I've been making progress but I'm pretty sure that what I'm writing is absolutely horrible non-idiomatic erlang. I will probably take you up on that but after I've learned a bit more so at least I stand half a chance of understanding you.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: