2012-02-06 69 views
2

我對scala相對陌生,並且成功地製作了一些非常簡單的程序。 但是,現在我正在嘗試一些現實世界的問題解決方案,事情變得越來越難......Scala - 嵌套循環,理解和最終迭代的類型

我想用'FileTypeReader'的各種'接受「某些文件(每個FileTypeReader子類型一個),並返回一個選項[配置],如果它可以從中提取配置。

我試圖避免勢在必行的風格,寫,對於爲例,這樣的事情(使用Scala的-10,scaladoc的路徑這裏http://jesseeichar.github.com/scala-io-doc/0.3.0/api/index.html#scalax.file.Path):

(...) 
trait FileTypeReader { 
    import scalax.file.Path 
    def accept(aPath : Path) : Option[Configuration] 
} 
var readers : List[FileTypeReader] = ...// list of concrete readers 
var configurations = for (
      nextPath <- Path(someFolder).children(); 
      reader <- readers 
    ) yield reader.accept(nextPath); 
(...) 

當然,這是不行的, for-comprehensions返回第一個生成器類型的集合(這裏是一些IterablePathSet)。

由於我嘗試了很多變體,感覺像是在圈內跑步,我懇求你對此提出建議以解決我的瑣碎問題? - 優雅的問題! :)

非常感謝提前,

sni。

+1

這是有點難,除非你告訴我們什麼元素的類型在comp rehension是 - 即'children()'返回什麼,'讀者'是什麼。 REPL示例對詢問Scala問題非常有用,因爲它們可以被REPLicated – 2012-02-06 14:54:49

+0

我編輯我的問題更清晰! – 2012-02-06 15:15:59

回答

4

如果我理解正確,您的問題是您有一個Set[Path]並且想要產生List[Option[Configuration]]。正如所寫,configurations將是一個Set[Option[Configuration]]。要改變這種爲List,使用toList方法即

val configurations = (for { 
    nextPath <- Path(someFolder).children 
    reader <- readers 
    } yield reader.accept(nextPath)).toList 

,或者改變發電機本身的類型:

val configurations = for { 
    nextPath <- Path(someFolder).children.toList 
    reader <- readers 
    } yield reader.accept(nextPath) 

你可能真的想要得到List[Configuration],你可以優雅地做因爲Option是一個monad:

val configurations = for { 
    nextPath <- Path(someFolder).children.toList 
    reader <- readers 
    conf  <- reader.accept(nextPath) 
    } yield conf 
+0

好,Luigi,那真是太棒了,正是我想要的!然而,任何人都可以解釋我爲什麼得到:「沒有從ScalaObject => scala.collection.TraversableOnce [B]可用的隱式視圖」當我嘗試'配置.flatten'你的第一個解決方案WITHOUT toList,以及爲什麼它工作得很好當我添加它? – 2012-02-06 19:47:59

+0

我不知道;它應該工作('設置(一些(1),無).flatten'編譯)。你在2.8之前沒有使用Scala的古老版本,對嗎?請參閱http://stackoverflow.com/questions/2895069/how-to-flatten-list-of-options-using-higher-order-functions – 2012-02-06 20:18:27

+0

不,2.9.1與sbt 0.11.2和scala.io 0.3.0 – 2012-02-06 20:48:28

0

您是否試圖找到第一個配置,它可以提取?如果不是,如果返回多個配置會發生什麼?

在第一種情況下,我只是得到理解的結果並且在其上調用find,這將返回Option

+0

你好,Daniel,好吧,我想要一個所有配置的Iterable(因此我的var名字)被發現! – 2012-02-06 15:08:03