在where子句下执行语句 [英] Do statement under a where clause
问题描述
我正在尝试使用 <-
绑定将 IO [String]
转换为[String]
;但是,我需要使用do
块在where
语句下执行此操作,但是Haskell始终抱怨缩进.这是代码:
I'm trying to convert IO [String]
to [String]
with <-
binding; however, I need to use a do
block to do that under a where
statement, but Haskell complains about the indentation all the time. Here is the code:
decompEventBlocks :: IO [String] -> IO [[String]]
decompEventBlocks words
| words' /= [] = block : (decompEventBlocks . drop $ (length block) words')
| otherwise = []
where
do
words' <- words
let block = (takeWhile (/="END") words')
这是什么原因?以及如何在 where
语句中使用 do
块?而且,我们是否有可能在警卫人员面前发表一些声明?
What is the reason for that ? And how can we use do
block in a where
statement ? Moreover, is there any chance that we can have some statements before the guards ?
推荐答案
记住:do
-块是语法糖表示单子符号.这意味着以下情况适用:
Remember: do
-blocks are syntactic sugar for monadic notation. This means the following applies:
do {a; b} = a >> b
dp {a <- b; c} = b >>= \a -> c
换句话说,当使用do
表示法时,实际上是在生成值.这就是为什么您不能在where
语句的顶层仅包含do
-block的原因.
In other words, when using do
-notation, you are actually producing values. This is why you can't just have a do
-block in the top level of your where
statement.
解决此问题的方法是将函数放入do
-block中:
The way to solve this is to put the function into a do
-block:
decompEventBlocks :: IO [String] -> IO [[String]]
decompEventBlocks words = do
-- We unwrap the IO [String], but we keep it in the do-block,
-- because it must be kept in a monadic context!
words' <- words
let block = (takeWhile (/="END") words')
-- This is equivalent to the guards you had in your function.
-- NB return :: Monad m => a -> m a, to keep it in a monadic context!
if not $ null words'
then do
-- Since the recursion is monadic, we must bind it too:
rest <- decompEventBlocks $ return $ drop (length block) words'
return $ block : rest
else return []
要了解有关monad,do
-符号,>>=
和>>
的信息,我强烈建议阅读 LYAH章节,以便在尝试更多单子代码之前获得良好的理解.
To learn about monads, do
-notation, >>=
, and >>
, I highly reccommend reading the LYAH chapters to gain a good understanding before attempting more monadic code.
这篇关于在where子句下执行语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!