Haskell - 循环播放用户输入 [英] Haskell - loop over user input

查看:109
本文介绍了Haskell - 循环播放用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在haskell中有一个程序需要读取用户输入的任意行,并在用户完成时累积输入必须发送给函数。在命令式编程语言中,这看起来像这样:

  content =''
而真:
line = readLine()
if line =='q':
break
content + = line
func(content)

我发现在haskell中做这件事非常困难,所以我想知道是否存在与haskell等价的东西。

解决方案

这在Haskell中相当简单。最棘手的部分是您想要累积用户输入的序列。在命令式语言中,您使用循环来完成此操作,而在Haskell中,规范的方法是使用递归辅助函数。它看起来像这样:

  getUserLines :: IO String  - 可选类型签名
getUserLines = go
where go = do
line< - getLine
if line ==q
然后返回内容
else go(contents ++ line ++ \ n) - 添加换行符

这实际上是一个IO操作的定义,它返回一个字符串。由于它是一个IO操作,因此可以使用< - 语法而不是 = 赋值语法来访问返回的字符串。如果你想快速浏览,我建议阅读为单纯不关心的人提供IO Monad。



您可以在GHCI提示符中使用此功能,例如

 >>> str<  -  getUserLines 
Hello< Enter> - 用户输入
World< Enter> - 用户输入
q< Enter> - 用户输入
>>> putStrLn str
Hello - 程序输出
世界 - 程序输出


I have a program in haskell that has to read arbitrary lines of input from the user and when the user is finished the accumulated input has to be sent to a function.

In an imperative programming language this would look like this:

content = ''
while True:
    line = readLine()
    if line == 'q':
        break
    content += line
func(content)

I find this incredibly difficult to do in haskell so I would like to know if there's an haskell equivalent.

解决方案

It's reasonably simple in Haskell. The trickiest part is that you want to accumulate the sequence of user inputs. In an imperative language you use a loop to do this, whereas in Haskell the canonical way is to use a recursive helper function. It would look something like this:

getUserLines :: IO String                      -- optional type signature
getUserLines = go ""
  where go contents = do
    line <- getLine
    if line == "q"
        then return contents
        else go (contents ++ line ++ "\n")     -- add a newline

This is actually a definition of an IO action which returns a String. Since it is an IO action, you access the returned string using the <- syntax rather than the = assignment syntax. If you want a quick overview, I recommend reading The IO Monad For People Who Simply Don't Care.

You can use this function at the GHCI prompt like this

>>> str <- getUserLines
Hello<Enter>     -- user input
World<Enter>     -- user input
q<Enter>         -- user input
>>> putStrLn str
Hello            -- program output
World            -- program output

这篇关于Haskell - 循环播放用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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