简体   繁体   中英

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.

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);

If you want to do this the lazy way (a generator), you can use @DenysSeguret's answer . If you want to produce a list of lists containing these numbers, you can do this as follows:

var triangles = [];
for (var i = 0; i < 10; i++) {
    for (var j = 0; j < 10; j++) {
        for (var k = 0; k < 10; k++) {
            triangles.push([i,j,k]);
        }
    }
}

fiddle

This being said since both Haskell and JavaScript are Turing complete languages , every program written in Haskell can be converted into a program written in JavaScript and vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM