等于(=)Vs左箭头(< ;-) haskell中的符号 [英] Equal (=) Vs left arrow (<-) symbols in haskell
问题描述
工作代码:
导入系统
main = do
[file1,file2]< - getArgs
- 复制文件内容
str< - readFile file1
writeFile file2 str
崩溃的代码:
import System
main = do
[file1, file2] = getArgs
str = readFile file1
writeFile file2 str
当我尝试,它会抛出一个错误:
a.hs:6:18:解析输入错误'='
因此, 对于IO monad的具体情况,例如在 来自允许闭包的命令式语言的程序员可以使用Javascript进行粗略的平行比较: 再次说明:此比较仅着重于IO。对于其他monads,您需要检查 < -
与 = $为了理解真正的区别,你必须了解monads,以及@rightfold描述的desugaring。他们的答案。
实际上是什么,并考虑解析
getArgs
示例中,一个粗略但有用的直觉可以做成如下:
x < - action
运行 IO / code>,得到结果,并将它绑定到
x
let x = action 定义
x
等价于 action
,但不会运行任何东西。稍后,您可以使用 y < - x
,这意味着 y < - action
。
$ b
var action = function(){print(3);返回5; }
//大致相当于x < - action
print('test 1')
var x = action()//输出:3
/ / x是5
//大致相当于让y =动作
print('test 2')
var y =动作//输出:nothing
/ / y是函数
//大致相当于z <-y
print('test 3')
var z = y()//输出:3
// z是5
do
。
Working code:
import System
main = do
[file1, file2] <- getArgs
--copy file contents
str <- readFile file1
writeFile file2 str
Crashing code:
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: parse error on input '='
So, how different is <-
from =
?
To understand the real difference, you have to understand monads, and the desugaring described by @rightfold in their answer.
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
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
.
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
Again: this comparison focuses on IO, only. For other monads, you need to check what >>=
actually is, and think about the desugaring of do
.
这篇关于等于(=)Vs左箭头(< ;-) haskell中的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!