将语法转换为>> =语法的简单示例 [英] Simple example on do syntax transformed to >>= syntax

查看:96
本文介绍了将语法转换为>> =语法的简单示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 reverse2lines 转换为使用>> = 语法?就像 addOneInt 被转换为 addOneInt'

 addOneInt :: IO()
addOneInt = do行< - getLine
putStrLn(show(1 + read line :: Int))


addOneInt':: IO()
addOneInt'= getLine>> = \line - >
putStrLn(show(1 + read line :: Int))

reverse2lines :: IO()
reverse2lines =
do line1< - getLine
line2 < - getLine
putStrLn(反向行2)
putStrLn(反向行1)

请考虑阅读后续的问题及其有价值的答案。

解决方案

您可以从您已知的内容中安全地推断出它。首先将您的 addOneInt'完全加圆括号:
$ b

  addOneInt'= getLine> ;> =(\ line  - > 
putStrLn(show(1 + read line :: Int)))

接下来,您可以将 reverse2lines 等效地写为

  reverse2lines = 
do {line1< - getLine;
do {line2< - getLine;
do {putStrLn(reverse line2);
do {putStrLn(reverse line1)}}}}

应用单步转换你已经用于 addOneInt ,根据需要多少次,你会得到

  reverse2lines':: IO()
reverse2lines'=
getLine>> =(\ line1 - >
getLine>> =(\line2 - >
putStrLn(reverse line2)>>
putStrLn(reverse line1)))

在语法上,可以忽略lambda表达式的括号,但是在这里明确地写出它们有助于澄清和明确这些函数的嵌套结构,特别是如果我们要排列缩进。



完全平移安排monad的失败函数在模式不匹配时被调用,但由于变量模式( line1 line2 )是无可辩驳的,这个翻译实际上是确切的。

How can reverse2lines transformed into the using >>= syntax ? Just like addOneInt is transformed into addOneInt'?

addOneInt :: IO () 
addOneInt = do line <- getLine
               putStrLn (show (1 + read line :: Int))      


addOneInt' :: IO ()
addOneInt' = getLine >>= \line ->
             putStrLn (show ( 1 + read line :: Int))  

reverse2lines :: IO () 
reverse2lines = 
 do line1 <- getLine 
    line2 <- getLine
    putStrLn (reverse line2) 
    putStrLn (reverse line1)

Please also consider reading the follow up question and its valuable answers.

解决方案

You could safely deduce it from what you already know. Start by fully parenthesizing your addOneInt':

addOneInt' = getLine >>= (\line ->
             putStrLn (show (1 + read line :: Int)) )

Next, you reverse2lines can be equivalently written as

reverse2lines = 
 do { line1 <- getLine ;
      do { line2 <- getLine ;
           do { putStrLn (reverse line2) ;
                do { putStrLn (reverse line1) } } } }

Applying the one-step transformation that you already used for addOneInt, as much times as needed, you'd get

reverse2lines' :: IO ()
reverse2lines' = 
    getLine  >>=  (\line1 ->
      getLine  >>=  (\line2 ->
        putStrLn (reverse line2)  >>
          putStrLn (reverse line1) ) )

Syntactically, the parentheses around lambda expressions can be omitted, but writing them explicitly here helps to clarify and make obvious the nested structure of these functions, especially if we'd line up the indentation.

Full translation arranges for the monad's fail function to be called on pattern mismatch, but since the variable patterns (line1, line2) are irrefutable, this translation is in fact exact.

这篇关于将语法转换为&gt;&gt; =语法的简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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