Scala 中的 Haskell do-notation 或 F# 计算表达式等效吗?

发布于 2024-12-05 10:44:41 字数 751 浏览 1 评论 0原文

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

但感觉不太对劲。有更好的语法吗?

例如,在 haskell 中,你会遇到

    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 语法似乎与列表理解有太强的耦合,这是一个独特的概念。这阻止了我编写看起来并不奇怪的内部 DSL(monad)。

F# Computation Expressions allow to hide the complexity of monadic syntax behind a thick layer of syntactic sugar. Is there something similar available in Scala?

I think it's for comprehensions ...

Example:

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

But it doesn't really feel right. Is there a better syntax?

for exemple in haskell you would have

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

this unlike scala doesn't look like a foreach loops.
Scala syntax seem to have too strong coupling with List comprehension which is a distinct concept. Which prevent me from writing internal DSL (monad) that doesn't look strange.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赴月观长安 2024-12-12 10:44:41

缺少的部分可能是 scala 的 for 理解中 = 的使用:

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

通过明智地混合 <-=,你应该有您需要的所有灵活性。

The missing piece is probably the use of = is scala's for-comprehensions:

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

With judicious mixing of both <- and =, you should have all the flexibility you need.

oО清风挽发oО 2024-12-12 10:44:41

scala 中似乎没有这样的语法,我们需要使用编译器插件架构自己实现它。

It seem like there is no such syntax available in scala and we would need to implement it ourself using the compiler plugin architecture.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文