LoginSignup
13
14

More than 5 years have passed since last update.

swiftのクロージャで多重ループを簡単に書いてみる

Last updated at Posted at 2015-09-24

Cで多重ループを簡単に書こうとすると以下のようにマクロでfor文を定義することができました。
これは多重ループを多用するような3Dの処理などでは、このようなソースをよく見ます。
ただし、C90ではコンパイルできなかったり、最近の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
}

これをswiftのクロージャで書くとこんな感じに定義することができます。

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

これと同じようにC#のParallel.For文のようなこともできるかもしれません。(使ったことないけど)
関数型言語はよくわかりませんが、こういう感じに今までの処理を置き換えていくと見えてくるものがあるかもしれないですね。

13
14
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
14