Scala中的副作用

编程入门 行业动态 更新时间:2024-10-19 20:25:46
本文介绍了Scala中的副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我在这些日子里正在学习Scala。我对Haskell有一点点的熟悉,尽管我不能说明自己很清楚。

对不熟悉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中的副作用

本文发布于:2023-11-14 00:32:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:副作用   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!