[英]Any way to append two monadic lists in Haskell?
I am learning Haskell at Uni this semester.我这学期在 Uni 学习 Haskell。 I encountered a problem where I have a list of lists as
IO [[String]]
and I want to append an IO [String]
to the first one.我遇到了一个问题,我的列表列表为
IO [[String]]
,我想将 append 和IO [String]
添加到第一个。
Lets denote them as x and y.让我们将它们表示为 x 和 y。 So I tried doing
y >>= return. (++) [x]
所以我尝试做
y >>= return. (++) [x]
y >>= return. (++) [x]
or y <> [x]
. y >>= return. (++) [x]
或y <> [x]
。 All of them gave the error: Could not match IO [[String]] with [IO [String]].
他们都给出了错误:
Could not match IO [[String]] with [IO [String]].
Any suggestions?有什么建议么? Thank you.
谢谢你。
In my opinion, the simplest general technique to learn is about how to use do
blocks.在我看来,要学习的最简单的通用技术就是如何使用
do
块。
test :: IO [[String]]
test = do
xss <- generateListOfLists -- IO [[String]]
xs <- generateList -- IO [String]
return (xss ++ [xs])
The idea is that <-
temporarily unwraps the monad, removing the IO
monad from types, as long as at the very end we return a value in the same monad (the return
at the end).这个想法是
<-
暂时解开 monad,从类型中删除IO
monad,只要在最后我们在同一个 monad 中返回一个值(最后return
)。
After one understands that general technique, one can then learn alternatives like applicative notation, which is not as general, but still nice.在理解了这种通用技术之后,就可以学习替代方法,例如应用符号,它不是那么通用,但仍然很好。
test :: IO [[String]]
test =
(\xss xs -> xss ++ [xs])
<$> generateListOfLists
<*> generateList
Using >>=
is less common, and at least in this case, less convenient than a do
block.使用
>>=
不太常见,至少在这种情况下不如do
块方便。
test :: IO [[String]]
test =
generateListOfLists >>= \xss ->
generateList >>= \xs ->
return (xss ++ [xs])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.