簡體   English   中英

在Scala中等效的Haskell標記或F#計算表達式?

[英]Equivalent of Haskell do-notation or F# Computation Expressions in Scala?

F#計算表達式允許隱藏厚層語法糖背后的一元語法的復雜性。 Scala中是否有類似的東西?

我認為這是為了理解......

例:

val f = for {
  a <- Future(10 / 2) // 10 / 2 = 5
  b <- Future(a + 1)  //  5 + 1 = 6
  c <- Future(a - 1)  //  5 - 1 = 4
 } yield b * c         //  6 * 4 = 24

 val result = f.get

但它確實感覺不對。 有更好的語法嗎?

例如,你可以擁有哈斯克爾

main = do fromHandle <- getAndOpenFile "Copy from: " ReadMode
          toHandle   <- getAndOpenFile "Copy to: " WriteMode 
          contents   <- hGetContents fromHandle
          hPutStr toHandle contents
          hClose toHandle
          putStr "Done."

這與scala不同,看起來不像是一個foreach循環。 Scala語法似乎與List comprehension有太強的耦合,這是一個獨特的概念。 這阻止我編寫看起來並不奇怪的內部DSL(monad)。

缺少的部分可能是使用=是scala的for -reherehension:

val f = for {
  a <- Future(10 / 2) // 10 / 2 = 5
  b <- Future(a + 1)  //  5 + 1 = 6
  c <- Future(a - 1)  //  5 - 1 = 4
  d = b * c           //  6 * 4 = 24
} yield d


val result = f.get

通過明智地混合<-= ,您應該具備所需的所有靈活性。

似乎scala中沒有這樣的語法,我們需要使用編譯器插件架構自己實現它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM