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

问题描述

我很难理解这一点.用do表示法书写时,下面两行有什么不同?

1.让 x = 表达式2. x 

我看不到.有时一个有效,有时另一个.但很少两者兼而有之.Learn you a haskell"表示 <- 将右侧绑定到左侧的符号.但这与简单地用 let 定义 x 有什么不同?

解决方案

<- 语句将从 monad 中提取值,而 let 语句不会.

import Data.TypeablereadInt :: 字符串 ->输入接口readInt s = 做putStrLn $ "输入" ++ s ++ "的值:"读入主要 = 做x 

运行时,程序会询问x的值,因为一元动作readInt "x"是由<-语句执行的.它不会询问 y 的值,因为对 readInt "y" 进行了评估,但不会执行由此产生的 monadic 操作.

输入 x 的值:123x :: 整数y :: IO 整数

由于x :: Int,你可以用它做普通的Int事情.

putStrLn $ "x = " ++ 显示 xputStrLn $"x * 2 = " ++ 显示(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

这篇关于“&lt;-"do 表示法中的绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 07:31