Scala 中的 Haskell do-notation 或 F# 计算表达式等效吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
缺少的部分可能是 scala 的 for 理解中
=
的使用:通过明智地混合
<-
和=
,你应该有您需要的所有灵活性。The missing piece is probably the use of
=
is scala's for-comprehensions:With judicious mixing of both
<-
and=
, you should have all the flexibility you need.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.