Monadic 组合并翻转丢弃 (>>)

xba*_*laj 6 monads haskell

函数的定义(>>)如下:

(>>) :: Monad m => m a -> m b -> m b

但我想实现这个功能翻转如下:

我有一个函数tabulate :: Int -> [Int] -> IO Int,它将列表打印为具有给定列数的表格,并返回 monad 中所有列表项的总和IO。之后我想要一个明确的putStr "\n".

如果我会使用以下内容:

tabulate >> (putStr "\n")

它会丢弃制表的结果,相反,它不会在表格后打印换行符。如果在以下位置执行此操作do

smth = do
   let a = tabulate
   putStr "\n"
   a
Run Code Online (Sandbox Code Playgroud)

这样做将再次在表格之前打印换行符,因为 是aputStr.

在制表函数之后如何打印换行符?

Wil*_*sem 10

您可以在这里工作(<*) :: Applicative f => f a -> f b -> f a

smth :: IO Int
smth = tabulate 14 [2, 5] <* putStr "\n"
Run Code Online (Sandbox Code Playgroud)

这相当于:

smth = do
   a <- tabulate 14 [2, 5]
   putStr "\n"
   return a
Run Code Online (Sandbox Code Playgroud)

因此,它首先评估 的IO Inttabulate 14 [2, 5]然后"\n"作为操作打印,但它“返回”调用的值tabulate,而不是调用的值putStr