等于 (=) 与 Haskell 中的左箭头 (<-) 符号 [英] Equal (=) Vs left arrow (<-) symbols in haskell

查看:51
本文介绍了等于 (=) 与 Haskell 中的左箭头 (<-) 符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

工作代码:

import System
main = do
     [file1, file2] <- getArgs
     --copy file contents
     str <- readFile file1
     writeFile file2 str

崩溃代码:

import System
main = do
       [file1, file2] = getArgs
       str = readFile file1
       writeFile file2 str

当我尝试时,它抛出了一个错误:

When I tried, it threw an error as:

a.hs:6:18:输入 '='

a.hs:6:18: parse error on input '='

那么,<-= 有什么不同?

So, how different is <- from =?

推荐答案

要了解真正的区别,您必须了解 monad,以及@rightfold 在他们的回答中描述的脱糖.

To understand the real difference, you have to understand monads, and the desugaring described by @rightfold in their answer.

对于 IO monad 的特定情况,如在您的 getArgs 示例中,可以做出如下粗略但有用的直觉:

For the specific case of the IO monad, as in your getArgs example, a rough but useful intuition can be made as follows:

  • x <- action 运行 IO action,得到它的结果,并绑定到x
  • let x = action 定义 x 等价于 action,但不运行任何东西.稍后,您可以使用 y <- x 表示 y <- action.
  • x <- action runs the IO action, gets its result, and binds it to x
  • let x = action defines x to be equivalent to action, but does not run anything. Later on, you can use y <- x meaning y <- action.

来自允许闭包的命令式语言的程序员,可能会与 JavaScript 进行粗略的平行比较:

Programmers coming from imperative languages which allow closures, may draw this rough parallel comparison with JavaScript:

var action = function() { print(3); return 5; }

// roughly equivalent to x <- action
print('test 1')
var x = action()  // output:3
// x is 5

// roughly equivalent to let y = action
print('test 2')
var y = action    // output: nothing
// y is a function

// roughly equivalent to z <- y
print('test 3')
var z = y()       // output:3
// z is 5

再次:这个比较只关注 IO.对于其他 monad,你需要检查 >>= 实际上是什么,并考虑 do 的脱糖.

Again: this comparison focuses on IO, only. For other monads, you need to check what >>= actually is, and think about the desugaring of do.

这篇关于等于 (=) 与 Haskell 中的左箭头 (&lt;-) 符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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