Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do this simple Haskell assignment in Javascript?

I'm going through this tutorial from learnyouahaskell.com and it shows how you can make a list of triangles with the following code

let triangles = [ (a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10] ]  

Apparently this produces a list of tuples (or is that triples?) of all the possible combinations of (x,y,z) where x, y and z are between 1-10.

I thought it would be fun to try and reproduce this in Javascript but I'm having no luck. Is there an elegant (yet readable) way of producing this in javascript using reduce/map etc..?

I'm looking for an array of arrays where each child array contains 3 numbers. I would post my code but I'm not even close to solving this so I don't think it would help.

like image 673
punkrockbuddyholly Avatar asked Jul 28 '26 10:07

punkrockbuddyholly


1 Answers

You seem to be looking for the nearest equivalent of list comprehension in today's JavaScript. Comprehensions are in stand-by for now in EcmaScript, we don't know if they'll be available soon. But we have generators. They're not as sexy but they might cover your need.

Here's what it could look like:

var triangles = (function*(){
  for (var i=0; i<10; i++){
    for (var j=0; j<10; j++){
      for (var k=0; k<10; k++){
          yield [i,j,k];
      }
    }
  }
})();


console.log(triangles.next().value); // [0, 0, 0]
console.log(triangles.next().value); // [0, 0, 1]
console.log(triangles.next().value); // [0, 0, 2]

As in Haskell you're not limited to finite lists.

You can iterate like this:

for (var t of triangles) console.log(t);

(of course, if your list is infinite, you'd better break at some point).

And if you need a concrete array (which kind of breaks the beauty of generators), then you can use Array.from as suggested by Bergi:

var triangleArray = Array.from(triangles);
like image 79
Denys Séguret Avatar answered Jul 29 '26 23:07

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!