"< - "在符号中绑定 [英] "<-" bindings in do notation

查看:225
本文介绍了"< - "在符号中绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难把握这一点。在写符号时,以下两行如何不同?

  1。让x =表达式
2. x < - 表达式

我看不到它。有时候一个人工作,一个人工作。但很少两个。 学习你一个haskell说,< - 将右侧绑定到左侧的符号。但是,与 let

< - 语句将从monad中提取值,并且 let
$ b

  import Data.Typeable 

readInt :: String - > IO Int
readInt s = do
putStrLn $为++ s ++输入值:
readLn

main = do
x< ; - readIntx
let y = readInty
putStrLn $x ::++ show(typeOf x)
putStrLn $y ::++ show typeOf y)

运行时,程序会询问x的值,因为monadic action readIntx< - 语句执行。它不会询问y的值,因为 readInty会被评估,但是不会执行产生的一元行为。

 
输入x的值:
123
x :: Int
y :: IO Int
$ b

既然 x :: Int ,你可以做普通的 Int

  putStrLn $x =++显示x 
putStrLn $x * 2 =++ show(x * 2)

由于 y :: IO Int ,你不能假装它是一个普通的 Int

  putStrLn $y =++ show y  - 错误
putStrLn $y * 2 =++ show(y * 2) - 错误


I have a hard time grasping this. When writing in do notation, how are the following two lines different?

1. let x = expression
2. x <- expression

I can't see it. Sometimes one works, some times the other. But rarely both. "Learn you a haskell" says that <- binds the right side to the symbol on the left. But how is that different from simply defining x with let?

解决方案

The <- statement will extract the value from a monad, and the let statement will not.

import Data.Typeable

readInt :: String -> IO Int
readInt s = do
  putStrLn $ "Enter value for " ++ s ++ ": "
  readLn

main = do
  x <- readInt "x"
  let y = readInt "y"
  putStrLn $ "x :: " ++ show (typeOf x)
  putStrLn $ "y :: " ++ show (typeOf y)

When run, the program will ask for the value of x, because the monadic action readInt "x" is executed by the <- statement. It will not ask for the value of y, because readInt "y" is evaluated but the resulting monadic action is not executed.

Enter value for x: 
123
x :: Int
y :: IO Int

Since x :: Int, you can do normal Int things with it.

putStrLn $ "x = " ++ show x
putStrLn $ "x * 2 = " ++ show (x * 2)

Since y :: IO Int, you can't pretend that it's a regular Int.

putStrLn $ "y = " ++ show y -- ERROR
putStrLn $ "y * 2 = " ++ show (y * 2) -- ERROR

这篇关于&QUOT;&LT; - &QUOT;在符号中绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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