0

我正在尝试重写一个小程序,该程序从一个或多个网页中抓取信息,然后将其转换为闪存卡。这里的小片段:

-- | this takes a string and produces IO [Tag String]
getVerbePage x = fmap parseTags $ openURL $ "http://leconjugueur.lefigaro.fr/conjugaison/verbe/" ++ x ++ ".html"

main = do
    tags <- getVerbePage "aller"
    -- | from here I do whatever I like with a clean [Tag String]

一次做一个我没有问题,IO进入do循环,然后我用纯函数做我需要做的事情。我真的不明白如何以重复的方式做到这一点,基本上我所追求的是:

-- | this takes a string and produces IO [Tag String]
getVerbePage x = fmap parseTags $ openURL $ "http://leconjugueur.lefigaro.fr/conjugaison/verbe/" ++ x ++ ".html"

main = do
    verbsString <- getLine -- | example input "aller pouvoir"
    let verbs = splitOn " " verbsString -- | list of strings
    pages <- getVerbePages verbs
    -- | from here use pure functions on pages, which would be type [[Tag String]]

getVerbePages :: [String] -> [[Tag String]] -- | I guess.
getVerbePages ps = ??????

问题是我如何编写 getVerbePages 来遍历 ps 中的每个字符串并干净地返回它?到目前为止,我已经能够很好地处理递归动作以及所有这些,非常像 Haskell 新手,但我不明白在重复 IO 动作时这一切是如何工作的。

4

1 回答 1

4

如果您想对IO一系列事物重复相同的操作,那么您可以使用mapM. 它的类型签名是(这里专门用于IO

mapM :: (a -> IO b) -> [a] -> IO [b]

与您一起使用它getVerbPage意味着a类型变量是String并且b类型变量是[Tag String]。然后你会有mapM getVerbPage :: [String] -> IO [[Tag String]],这就是你想要的定义getVerbPages

于 2012-05-19T10:16:45.303 回答