在">> ="中添加一个额外的步骤

dar*_*rko 0 haskell

我有这个工作正常:

forM_ [1..10] $ \x -> myFunc1 x 99 >>= putStrLn . show >> return ()

myFunc1 :: Int -> Int -> IO Bool
myFunc1 .....
Run Code Online (Sandbox Code Playgroud)

我想在输出中添加一个额外的字符串:

   forM_ [1..10] $ \x -> myFunc1 x 99 >>= (++) "the result is: " >>= putStrLn . show >> return ()
Run Code Online (Sandbox Code Playgroud)

但那不编译.我尝试了不同的变化,但仍然没有成功.你的建议?

Eri*_*ikR 7

突出的第一件事就是表达:

(++) "the result is: "
Run Code Online (Sandbox Code Playgroud)

不是IO动作 - 它只是一个纯函数String - > String,这就是为什么你的代码不是类型检查的一个原因.

要将其转换为IO动作,您可以使用以下命令进行组合return:

return . ( (++) "the result is: " )
  :: String -> IO String
Run Code Online (Sandbox Code Playgroud)

现在你可以用它了>>=.

然而,这不是真正的问题所在......

要在show你必须在putStrLn调用中插入它之前添加"结果是:" :

... >>= putStrLn . (++ "the result is: ") . show
Run Code Online (Sandbox Code Playgroud)

(注意,不需要>> return ()因为putStrLn已经返回()).

老实说,使用do-notation要简单得多:

forM_ [1..10] $ \x -> do
  s <- myFunc1 x 99
  putStrLn $ "the result is: " ++ show s
Run Code Online (Sandbox Code Playgroud)