对不熟悉Haskell的人的括号说明
我在Haskell中喜欢的一个特征是,不仅函数是一等公民,而且副作用(让我称之为行为)是。一个动作,当它被执行时,会赋予你一个类型 a 的值,属于特定类型 IO a 。你可以像任何其他值一样传递这些动作,并将它们以有趣的方式组合在一起。
实际上,组合的副作用是在Haskell中与他们做某事的唯一方法,因为你不能执行它们。相反,执行 的程序是由 main 函数返回的组合动作。这是一个巧妙的技巧,允许函数是纯粹的,同时让程序实际上做一些事情,而不是耗电。
这种方法的主要优点是编译器了解代码中执行副作用的部分,因此它可以帮助您找出错误。
实际问题
在Scala中是否有某种方法让编译器类型检查副作用,例如 - 保证不会在某个函数中执行副作用?不,这在原则上不可能在Scala中实现,因为语言不强制引用透明性 - 语言语义不会被忽视副作用。你的编译器不会跟踪和强制你的副作用。
你将能够使用类型系统标记一些动作为<$ c然而,在程序员纪律下,获得一些编译器支持,但是没有编译器证明。
I am learning Scala right in these days. I have a slight familiarity with Haskell, although I cannot claim to know it well.
Parenthetical remark for those who are not familiar with Haskell
One trait that I like in Haskell is that not only functions are first-class citizens, but side effects (let me call them actions) are. An action that, when executed, will endow you with a value of type a, belongs to a specific type IO a. You can pass these actions around pretty much like any other value, and combine them in interesting ways.
In fact, combining the side effects is the only way in Haskell to do something with them, as you cannot execute them. Rather, the program that will be executed, is the combined action which is returned by your main function. This is a neat trick that allows functions to be pure, while letting your program actually do something other than consuming power.
The main advantage of this approach is that the compiler is aware of the parts of the code where you perform side effects, so it can help you catch errors with them.
Actual question
Is there some way in Scala to have the compiler type check side effects for you, so that - for instance - you are guaranteed not to execute side effects inside a certain function?
解决方案No, this is not possible in principle in Scala, as the language does not enforce referential transparency -- the language semantics are oblivious to side effects. Your compiler will not track and enforce freedom from side effects for you.
You will be able to use the type system to tag some actions as being of IO type however, and with programmer discipline, get some of the compiler support, but without the compiler proof.
更多推荐
Scala中的副作用
发布评论