单子如何被认为是纯的? [英] How Monads are considered pure?

查看:35
本文介绍了单子如何被认为是纯的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Haskell 非常陌生,并且对该语言的架构"印象深刻,但仍然困扰着我 monads 如何可以是纯粹的.

I am very much new to Haskell, and really impressed by the language's "architecture", but it still bothers me how monads can be pure.

由于您拥有任何指令序列,这使它成为一个不纯的函数,尤其是具有 I/O 的函数从任何角度来看都不是纯函数.

As you have any sequence of instructions, it makes it an impure function, especially functions with I/O wouldn't be pure from any point of view.

是不是因为 Haskell 像所有纯函数一样假设 IO 函数也有返回值,但是以操作码或其他形式的?我真的很困惑.

Is it because Haskell assumes, like all pure functions, that IO function has a return value too, but in form of opcode or something? I am really confused.

推荐答案

一种思考方式是 IO a 类型的值是一个配方",包含指令列表如果执行会产生副作用.构建该食谱"虽然没有任何副作用.因此,haskell 程序(其类型为 IO ())基本上是构建此类配方的计算.重要的是,该程序不会执行配方中的任何指令.当配方完成时,程序终止.然后编译器(或解释器)采用该配方并执行它.但是程序员编写的代码不再运行,所以配方中的指令在程序范围之外执行.

One way to think of this is that a value of type IO a is a "recipe", containing a list of instructions that if performed would have side effects. Constructing that "recipe" though, does not have any side effects. So a haskell program (whose type is IO ()) is basically a computation that constructs such a recipe. Importantly, the program does not execute any of the instructions in the recipe. When the recipe is completed the program terminates. Then the compiler (or interpreter) takes that recipe and executes it. But the code that the programmer wrote is not running anymore, so the instructions in the recipe are executed outside the scope of the program.

这篇关于单子如何被认为是纯的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆