OK、私はここで愚かなこと (Scala の新機能) に苦労しているに違いありません。
Action
名前(問題とは関係ありません)とリストパラメータを取るクラスがあります。
各パラメーターには可能な値のセットがあり、のパラメーターに対して可能な引数の完全なリストを生成したいと考えていますAction
。私は a を使用しようとしましたfor-comprehension
が、すべての引数を入力するのではなく、1 つの値だけを置き換えた組み合わせを取得しています。
私のコードは次のようになります (問題を説明するために単純化しました):
case class ParamType(name: String)
{
def matchesType(that: ParamType): Boolean =
this.name == that.name
}
sealed abstract class Param (paramType : ParamType)
case class VarParam(parameter : String, paramType : ParamType) extends Param (paramType)
case class ValueArg(name : String, paramType : ParamType) extends Param(paramType)
case class Action(name: String, params: List[Param])
{
def possibleActions(possibleValues : Set[ValueArg]) : Set[Action] =
for {
parameter <- params.collect({case pt: VarParam => pt})
argument <- possibleValues
if (argument.matchesType(parameter))
} yield replaceParam(parameter, argument)
def replaceParam(parameter: VarParam, argument: ValueArg) : Action =
{
val i = parameters.indexOf(parameter)
if (i >= 0)
Action(name, parameters.updated(i, argument)
}
}
object tester {
def main(args: Array[String]) {
val possibleValues = Set[ValueArg](new ValueArg("a1", new ParamType("Atype")),
new ValueArg("a2", new ParamType("Atype")),
new ValueArg("a3", new ParamType("Atype")),
new ValueArg("b1", new ParamType("Btype")),
new ValueArg("b2", new ParamType("Btype")),
new ValueArg("b3", new ParamType("Btype")),
new ValueArg("c1", new ParamType("Ctype")),
new ValueArg("c2", new ParamType("Ctype")),
new ValueArg("c3", new ParamType("Ctype")))
val action1 = new Action("action1", List[Param](new VarParam("A", new ParamType("Atype")), new VarParam("B", new ParamType("Btype")), new VarParam("C", new ParamType("Ctype"))))
val possibleActions = action1.possibleActions(possibleValues)
println(possibleActions)
}
}
この関数replaceParam
は、パラメーターが引数に置き換えられたアクションを返すだけです。
したがって、パラメーター A、B、C を持つ action1 があり、それぞれが {a1、a2、a3}、{b1、b2、b3}、および {c1、c2、c3} を取ることができる場合 (それらは同じ型であると仮定します) 、私は次のようになります:
action1(a1, B, C) , action1(A, b1, C), action1(A, B, c1), action1(a2, B, C) など
しかし、私が欲しいのは:
action1(a1, b1, c1), action1(a1, b1, c2), action1(a2, b1, c1) など
これを達成するための最もエレガントな方法は何ですか?