【发布时间】:2019-04-19 08:50:03
【问题描述】:
我在 Haskell 中遇到了惰性 IO 问题。尽管阅读了该领域的其他问题,但我无法弄清楚如何解决我的具体案例。
我正在使用手术刀包来解析 html。用例很简单:一个站点包含指向描述某种事件的其他站点的链接。所以我写了以下结构(我在这里省略了一些实现):
type Url = String
-- function that parses all urls
allUrls :: Url -> IO (Maybe [Url])
data Event = Event { ... }
-- function that parses an event
parseEvent :: Url -> IO (Maybe Event)
-- function that writes the event to a file
doThings :: Url -> IO ()
doThings url = return url >>= parseEvent >>= (appendFile "/tmp/foo.txt" . show)
-- function that should take all urls and write their events to a file
allEvents :: IO (Maybe [Url]) -> IO (Maybe (IO [()]))
allEvents urls = urls >>= return . liftM (mapM doThings)
-- or alternatively:
-- function that takes all urls and returns all events
allEvents :: IO (Maybe [Url]) -> IO (Maybe (IO [Maybe Event]))
allEvents urls = urls >>= return . liftM (mapM parseEvent)
-- some function that writes all events to a file
allEventsToFile :: IO (Maybe (IO [Maybe Event])) -> IO()
???
doThings 函数按预期工作。给定一个 url,它会解析相应的事件并将其写入文件。但是 allEvents 由于懒惰而完全没有做任何事情。如何强制在 allEvents 中进行评估?
【问题讨论】:
-
你需要你的
allEvents有IO (Maybe [Url]) -> IO ()的类型
标签: haskell file-io io html-parsing lazy-evaluation