LoginSignup
11
13

More than 5 years have passed since last update.

C#とScalaで関数型言語プログラミング

Posted at

C#でラムダ式が使えるということで・・・

次のScalaとC#のコードは同じ意味です。

confrim.cs
   class Program
    {
        static void Main(string[] args)
        {
            loopCall(10, nTimes(5));
        }

        static void loopCall(int max, Func<int, int> func)
        {
            for (int i = 1; i < max+1; i++)
            {
                Console.Write(func(i) + " ");
            }
        }

        static Func<int, int> nTimes(int times)
        {
            return n => n * times;
        }
    }
confrim.scala
object Plactice{
    def main(args: Array[String]){
        loopCall(10, nTimes(5))
    }

    def loopCall(n:Int, func:(Int) => Int) ={
        for(i <- 1 to n)
            print(func(i) + " ")

                println
    }

    def nTimes(times : Int) : (Int) => Int = {
        (value : Int) => value * times;
    }
}

出力結果
5 10 15 20 25 30 35 40 45 50

関数型言語Scalaと比べて、関数型言語の様な記述を取り入れたに過ぎないC#はちょっと書き方が面倒ですね。Func型を新たに利用しているのが面倒です。ラムダ式なんだから、main内で定義しても良かったのですが、そこはScalaのコードと退避させるという意味合いで...

ラムダ式なんてややこし言い方をするから、ややこしくなるのであって要は「処理を動的に変更可能な関数」を受け渡せること、と自分の中で理解。

しかし、C#はわりとJavaと対等な存在として説明されている気がしますが、言語仕様の拡張や改良でガンガン変わるC#と、ほとんど変わらないJava。あげくに、言語の開発者に見捨てられてJVMで動く別の言語ということになったりと・・・。この差はどこでついたんでしょうかね。

11
13
0

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
11
13