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

查看:261
本文介绍了等于(=)Vs左箭头(&lt ;-) 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的具体情况,例如在 getArgs 示例中,一个粗略但有用的直觉可以做成如下:


  • x < - action 运行 IO / code>,得到结果,并将它绑定到 x

  • let x = action 定义 x 等价于 action ,但不会运行任何东西。稍后,您可以使用 y < - x ,这意味着 y < - action


  • $ b

    来自允许闭包的命令式语言的程序员可以使用Javascript进行粗略的平行比较:

      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

    再次说明:此比较仅着重于IO。对于其他monads,您需要检查>> = 实际上是什么,并考虑解析 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 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.

    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左箭头(&lt ;-) haskell中的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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