Let's easily write multiple loops with swift closure

When I tried to write a multiple loop easily in C, I was able to define a for statement with a macro as follows. This is often seen in such sources, such as in 3D processing where multiple loops are heavily used. However, I think that it is common that you can not compile with C90, or you can not describe processing with macros in now and young languages such as recent swift.

nested_loop.c


#include <stdio.h>
#include <stdlib.h>

#define N 10
#define START_LOOP for(int i=0; i < N; i++){\
				   for(int j=0; j < N; j++){\
				   for(int k=0; k < N; k++){
#define END_LOOP }}}

int main(){
	START_LOOP
		printf("%d %d %d\n",i,j,k);
	END_LOOP
}

If you write this in a swift closure, you can define it like this.

nested_loop.swift


let N = 10;

func nested_loop(closure:(Int,Int,Int)->()){
  for i in 0..<N {
    for j in 0..<N{
      for k in 0..<N{
        closure(i,j,k)
      }
    }
  }
}

nested_loop({(i,j,k) in
  print(i,j,k)
})

nested_loop({
  print($0,$1,$2)
})

You could do something like the C # Parallel.For statement as well. (I have never used it) I'm not sure about functional languages, but if you replace the processing so far with something like this, you may see something like this.

Recommended Posts

Let's easily write multiple loops with swift closure
[Swift] Closure
[Swift / For beginners] Write smartly with type inference
Let's write Java file input / output with NIO
Upload multiple images easily with rails rails + carrierwave + cloudinary
Let's write Javadoc