开发者

possible to make some output in do notation and then return a String in haskell?

开发者 https://www.devze.com 2023-02-28 03:37 出处:网络
is it possible in haskell, to make some operations live output and then return a string with a function like:

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开发者_JAVA技巧 = do
    putStrLn x
    -- make some stuff
    return "abc"


Yes it is. But then, your function test must be an IO function too. So you have to write test :: String -> IO String as it's type instead. Also, the usage is different then. You have to „Unwrap“ the value first:

 -- instead of
 if (test string == "abc") then ...
 -- you have to write
 do string' <- test string -- unwrap
    if (string' == "abc") then ...

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 from Debug.Trace. It has the type trace :: 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消