Haskell &引用<-&引用;do表示法中的绑定

Haskell &引用<-&引用;do表示法中的绑定,haskell,binding,Haskell,Binding,我很难理解这一点。用do符号书写时,以下两行有什么不同 1. let x = expression 2. x <- expression 1。设x=表达式 2.x在let表单中,表达式是非一元值,而的右侧显示翻译): 及 do{x操作>>=(\x->do{rest}) 在let绑定中,表达式可以有任何类型,您所做的只是给它一个名称(或其内部结构上的模式匹配) 在=和)中,x>=\x->和表达式(本身,没有。这只是为定义长的单元计算链提供了更方便的语法,否则这些单元计算链往往会形成大量令人

我很难理解这一点。用do符号书写时,以下两行有什么不同

1. let x = expression
2. x <- expression
1。设x=表达式

2.x在
let
表单中,
表达式
是非一元值,而
的右侧显示翻译):

do{x操作>>=(\x->do{rest})

let
绑定中,表达式可以有任何类型,您所做的只是给它一个名称(或其内部结构上的模式匹配)

=
)中,
x>=\x->
表达式
(本身,没有
。这只是为定义长的单元计算链提供了更方便的语法,否则这些单元计算链往往会形成大量令人印象深刻的嵌套lambda


let
绑定根本不去糖,真的。
do
块中的
let
do
块外的
let
之间唯一的区别是
do
版本不需要
in
关键字跟随;它绑定的名称隐含在
其余部分的范围内e> do
block.

Haskell通过将命令式操作表示为形式类型
IO a
:产生类型
a
结果的命令式操作的类型,将副作用命令式编程与纯函数式编程协调起来

这样做的后果之一是,将变量绑定到表达式的值和将其绑定到执行操作的结果是两件不同的事情:

x <- action        -- execute action and bind x to the result; may cause effect
let x = expression -- bind x to the value of the expression; no side effects
line1++line2::String
是一个纯表达式,必须与
let
一起使用:

do line1 <- getLine            -- executes an action
   line2 <- getLine            -- executes an action
   let joined = line1 ++ line2 -- pure calculation; no action is executed
   return joined

do line1下面是一个简单的示例,向您展示了不同之处。
考虑下面两个简单的表达式:

letExpression = 2
bindExpression = Just 2
您试图检索的信息是编号
2
。 以下是您的操作方法:

let x = letExpression
x <- bindExpression
让x=letExpression

x
只为任意值指定一个名称或模式匹配

对于

putStrLn $ "x = " ++ show x
putStrLn $ "x * 2 = " ++ show (x * 2)
putStrLn $ "y = " ++ show y -- ERROR
putStrLn $ "y * 2 = " ++ show (y * 2) -- ERROR
x <- action        -- execute action and bind x to the result; may cause effect
let x = expression -- bind x to the value of the expression; no side effects
do line <- getLine -- side effect: read from stdin
   -- ...do stuff with line
do line1 <- getLine            -- executes an action
   line2 <- getLine            -- executes an action
   let joined = line1 ++ line2 -- pure calculation; no action is executed
   return joined
letExpression = 2
bindExpression = Just 2
let x = letExpression
x <- bindExpression
add m1 m2 = do
   v1 <- m1
   v2 <- m2
   return (v1 + v2) 
main  = print $ add [1, 2, 3] [40, 50]
--[41,51,42,52,43,53]
main  = print $ add (Just 3) (Just 12)
--Just 15
main  = print $ add (Just 3) Nothing
--Nothing