可以用 do 表示法进行一些输出,然后在 haskell 中返回一个字符串吗?
在haskell中是否可以使某些操作实时输出,然后返回一个具有如下函数的字符串:
test :: String -> String
test x = do
putStrLn x
-- make some stuff
return "abc"
is it possible in haskell, to make some operations live output and then return a string with a function like:
test :: String -> String
test x = do
putStrLn x
-- make some stuff
return "abc"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。但是,您的函数
test
也必须是一个IO
函数。所以你必须写test :: String -> IO String
因为它是类型。而且,用法也不一样。您必须首先“解开”该值:我可以理解,有时需要在纯计算深处的某个地方打印调试消息。对于这个特殊的用例,有来自
Debug.Trace
的trace
函数。它的类型为trace :: String ->一个-> a
,它打印出第一个参数,然后返回第二个参数。如果您编写一个复杂的程序并想验证它是否有效,这通常很有用。但请注意:您无法预测何时打印消息或是否打印消息。它可能出现一次两次或根本不出现,具体取决于编译器的心情。Yes it is. But then, your function
test
must be anIO
function too. So you have to writetest :: String -> IO String
as it's type instead. Also, the usage is different then. You have to „Unwrap“ the value first:I can understand, that there is sometimes the need to print a debug message somewhere deep inside a pure computation. For this special usecase, there is the function
trace
fromDebug.Trace
. It has the typetrace :: String -> a -> a
, it prints out it's first argument and then returns it second. This is often useful, if you write a complicated program and want to verify it works. But beware: You cannot predict when the message is printed or whether it is printed. It may appear once twice or not at all, depending on the compilers mood.