等于 (=) 与 Haskell 中的左箭头 (<-) 符号 [英] Equal (=) Vs left arrow (<-) symbols in 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
运行 IOaction
,得到它的结果,并绑定到x
let x = action
定义x
等价于action
,但不运行任何东西.稍后,您可以使用y <- x
表示y <- action
.
x <- action
runs the IOaction
, gets its result, and binds it tox
let x = action
definesx
to be equivalent toaction
, but does not run anything. Later on, you can usey <- x
meaningy <- 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 中的左箭头 (<-) 符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!