Monadic compose with discarding (>>) 翻转
Monadic compose with discarding (>>) flipped
(>>)
函数的定义如下:
(>>) :: Monad m => m a -> m b -> m b
但是我想像下面这样实现翻转的功能:
我有一个函数 tabulate :: Int -> [Int] -> IO Int
,它将列表打印为具有给定列数的 table 和 returns IO
中所有列表项的总和] 单子。
之后我想要一个明确的 putStr "\n"
.
如果我要使用以下内容:
tabulate >> (putStr "\n")
它会丢弃制表的结果,反之则不会在 table 之后打印换行符。
如果在 do
中执行此操作:
smth = do
let a = tabulate
putStr "\n"
a
这将再次在 table 之前打印换行符,因为 a
在 putStr
之后计算。
如何在制表函数后打印换行符?
您可以在此处使用 (<*) :: Applicative f => f a -> f b -> f a
:
smth :: IO Int
smth = tabulate 14 [2, 5] <strong><*</strong> putStr "\n"
这相当于:
smth = do
<strong>a</strong> <- tabulate 14 [2, 5]
putStr "\n"
return <strong>a</strong>
因此它首先评估 tabulate 14 [2, 5]
的 IO Int
,然后打印 "\n"
作为动作,但它“returns” [=14= 的值] 调用,而不是 putStr
调用。
(>>)
函数的定义如下:
(>>) :: Monad m => m a -> m b -> m b
但是我想像下面这样实现翻转的功能:
我有一个函数 tabulate :: Int -> [Int] -> IO Int
,它将列表打印为具有给定列数的 table 和 returns IO
中所有列表项的总和] 单子。
之后我想要一个明确的 putStr "\n"
.
如果我要使用以下内容:
tabulate >> (putStr "\n")
它会丢弃制表的结果,反之则不会在 table 之后打印换行符。
如果在 do
中执行此操作:
smth = do
let a = tabulate
putStr "\n"
a
这将再次在 table 之前打印换行符,因为 a
在 putStr
之后计算。
如何在制表函数后打印换行符?
您可以在此处使用 (<*) :: Applicative f => f a -> f b -> f a
:
smth :: IO Int
smth = tabulate 14 [2, 5] <strong><*</strong> putStr "\n"
这相当于:
smth = do
<strong>a</strong> <- tabulate 14 [2, 5]
putStr "\n"
return <strong>a</strong>
因此它首先评估 tabulate 14 [2, 5]
的 IO Int
,然后打印 "\n"
作为动作,但它“returns” [=14= 的值] 调用,而不是 putStr
调用。