4

C#には、基本的に次のように書く代わりに、メソッドグループと呼ばれる非常に便利なものがあります。

someset.Select((x,y) => DoSomething(x,y))

あなたは書ける:

someset.Select(DoSomething)

Scalaに似たようなものはありますか?

例えば:

int DoSomething(int x, int y)
{
    return x + y;
}

int SomethingElse(int x, Func<int,int,int> f)
{
    return x + f(1,2);
}

void Main()
{
    Console.WriteLine(SomethingElse(5, DoSomething));
}
4

3 に答える 3

10

Scalaでは、これを関数と呼びます;-)。(x,y) => DoSomething(x,y)は無名関数またはクロージャですが、この場合は、呼び出しているメソッド/関数のシグネチャに一致する任意の関数を渡すことができますmap。たとえば、scalaでは簡単に書くことができます

List(1,2,3,4).foreach(println)

また

case class Foo(x: Int)
List(1,2,3,4).map(Foo) // here Foo.apply(_) will be called
于 2012-07-20T18:47:17.843 に答える
1

いくつかの実験の結果、ScalaでもC#と同じように機能するという結論に達しました(実際に同じかどうかはわかりませんが...)

これは私が達成しようとしていたことです(Playで遊んでいるので、Scalaは私にとって初めてです。なぜこれが私の見解では機能しなかったのかわかりませんが、インタープリターで試してみると問題なく機能します)

def DoStuff(a: Int, b : Int) = a + b

def SomethingElse(x: Int, f (a : Int, b: Int) => Int)) = f(1,2) + x

SomethingElse(5, DoStuff)    
res1: Int = 8
于 2012-07-20T19:49:30.170 に答える
0

部分関数を使用して、メソッドグループの動作を実際にシミュレートできます。ただし、実行時にタイプエラーを強制的に発生させるだけでなく、呼び出すオーバーロードを決定するためにいくらかのコストが発生するため、これはおそらく推奨されるアプローチではありません。しかし、このコードはあなたが望むことをしますか?

object MethodGroup extends App {
   //The return type of "String" was chosen here for illustration
   //purposes only. Could be any type.
   val DoSomething: Any => String = {
        case () => "Do something was called with no args"
        case (x: Int) => "Do something was called with " + x
        case (x: Int, y: Int) => "Do something was called with " + (x, y)
    }

    //Prints "Do something was called with no args"
    println(DoSomething())

    //Prints "Do something was called with 10"
    println(DoSomething(10))

    //Prints "Do something was called with (10, -7)"
    println(DoSomething(10,-7))

    val x = Set((), 13, (20, 9232))
    //Prints the following... (may be in a different order for you)
    //Do something was called with no args
    //Do something was called with 13
    //Do something was called with (20, 9232)
    x.map(DoSomething).foreach(println)
}
于 2012-07-20T19:25:53.560 に答える