-1

私はこれを達成したいと思います:

複雑な処理の結果が真である場合を除き、abc という名前の変数は None でなければなりません。私は冒頭と答えを書きましたが、うまくいきません:

def abc={
None
copie.getRoot().asInstanceOf[DefaultMutableTreeNode].children() foreach ({
    site => <...more things after...>
} 

<more things after> で、結果を見つけることができます。例: Some(site)

しかし、コンパイラはこの順序を受け入れません。つまり、「None」の後にいくつかの条件が続き、最終的に Some(xxx) で終了します。条件の後に "None" を指定すると、もちろん結果は常に "None" になり、期待どおりではありません。

このように機能するかどうか、またどのように機能するか教えていただけますか? または、どうすれば続行できますか?


@Robin:あなたは正しいと思いました:Javaにある場合のように考えました:結果はNoneまたはSome(xxx)のいずれかである必要がありますが、驚くべきことに、ブロックの先頭に「None」を配置し、「None」の後に条件ステートメントを配置すると、 EVENTIUALYLYはSome(xxx)を返しますが、Eclipseのコンパイラは私のコードを受け入れません。したがって、最初の質問は次のようになります: この順序は (None の後にいくつかの条件付き処理が続き、最終的に Some(xxx) を返しますか? 例:

def abc():Option[DefaultMutableTreeNode]={
    None
    MyTree.getRoot().children() foreach{site=>
        if (site.toBeImported()) Some(site)
            else site.children() foreach {type=>
                if (type.toBeImported()) Some(type)
        }
    }
}  

ここで、この関数は None を返します。サイトが "toBeImported" の場合は Some(site) (複数ある場合は最後のものが返されます)、タイプが "toBeImported" の場合は Some(type) (最後のサイト) を返します。これは私のプログラムにあるものではありませんが、アイデアをうまく​​要約しています。

4

1 に答える 1

1

これがあなたの意図したものかどうかはわかりませんが、私の試みは次のとおりです。

object CondSO extends App {
  def condition(site: String): Boolean = site.contains("flow")

  def complexCalc(db: List[String]) = db.filter(condition)

  // abc is not a variable (as addressed in original Q), but rather a method
  def abc(db: List[String]): Option[String] =
  // orig. Q was a bit confusing what result is - boolean or something else?
  // so, here it's returning a list of results
    complexCalc(db).headOption

  // second version - the "for" approach
  def abc2(db: List[String]): Option[String] = (
    for (site <- db if condition(site)) yield site
    ).headOption

  // third version - using return
  // probably fastest option. IMO other options could be
  // similarly fast if they would be rewritten to use stream
  // (they construct auxiliary list with all matching sites, not only first one)
  def abc3(db: List[String]): Option[String] = {
    for (site <- db if condition(site)) return Some(site)
    None
  }

  // last version - custom foreach
  implicit class IterablePimps[A](val i: Iterable[A]) {
    def foreachWithReturn[B](f: A => Option[B]): Option[B] = {
      while (i.iterator.hasNext)
        f(i.iterator.next()) match {
          case a: Some[B] => return a
          case _ =>
        }
      None
    }
  }

  def abc4(db: List[String]): Option[String] =
    db.foreachWithReturn(s => if (condition(s)) Some(s) else None)

  // testing section
  val dbs = Map[String, List[String]](
    "empty  " -> List(),
    "present" -> List("google.com", "stackoverflow.com"),
    "absent " -> List("root.cz", "abclinuxu.cz")
  )

  val funcs = Map[String, (List[String]) => Option[String]](
    "filter" -> abc,
    "for   " -> abc2,
    "return" -> abc3,
    "pimp  " -> abc4
  )

  for {
    db <- dbs
    f <- funcs
  } println(s"Applying ${f._1} on list ${db._1}: ${f._2(db._2)}")
}

出力:

Applying filter on list empty  : None
Applying for    on list empty  : None
Applying return on list empty  : None
Applying pimp   on list empty  : None
Applying filter on list present: Some(stackoverflow.com)
Applying for    on list present: Some(stackoverflow.com)
Applying return on list present: Some(stackoverflow.com)
Applying pimp   on list present: Some(stackoverflow.com)
Applying filter on list absent : None
Applying for    on list absent : None
Applying return on list absent : None
Applying pimp   on list absent : None

編集: オプションのリストではなく、1 つの結果を返すようにメソッドを変更しました。より多くの可能な解決策を追加しました(質問者からの新しい情報に基づく)

于 2013-08-18T08:14:12.897 に答える