Monads如何被认为是纯粹的? [英] How Monads are considered Pure?

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

问题描述

我对Haskell非常陌生,对语言的架构印象深刻,但它仍然令我困扰, monads 可以是纯粹的。



当你有任何指令序列时,它使它成为不纯的函数,尤其是使用I / O的函数不会是纯粹从任何角度来看。



是否因为Haskell假设像所有纯函数一样, IO 函数具有也是一个返回值,但是以操作码的形式呢?我真的很困惑。

解决方案

有一种方法可以想到, IO a 是一个配方,包含一系列指令,如果执行会有副作用。构建这个配方虽然没有任何副作用。所以一个haskell程序(其类型是 IO())基本上是一个构造这样一个配方的计算。重要的是,程序不会执行配方中的任何指令。配方完成后,程序终止。然后编译器(或解释器)接受该配方并执行它。但是程序员编写的代码不再运行,所以配方中的指令在程序范围之外执行

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.

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.

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.

解决方案

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.

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

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