gpt4 book ai didi

haskell - haskell : how to force evaluation of functions and write to a file sequentially?

转载 作者:行者123 更新时间:2023-12-02 16:09:38 25 4
gpt4 key购买 nike

我在 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 内进行评估?

最佳答案

不是惰性 IO 的问题。惰性 IO 是指您从文件中读取惰性字符串,但不对其进行求值 - 在这种情况下,运行时将推迟实际读取直到您对其进行求值。

问题实际上是您在 allEvents没有执行任何 IO – 你只是在 IO 中随意调整值仿函数。这些值恰好是 IO行动本身,但这并不重要。具体来说,a >>= return . f始终与 fmap f a 相同,由单子(monad)定律。并且IO中的fmapping不绑定(bind)action。

这个问题已经在类型签名中观察到:-> IO (Maybe (IO [()]))表示该函数会产生 IO 操作,您可以稍后执行。但在这种情况下,您希望在执行allEvents时执行所有内容。 。所以签名可能是

allEvents :: IO (Maybe [Url]) -> IO ()

(或者可能 -> IO (Either EventExecError ()) ,如果你想正确处理失败)。

这可能仍然不是您想要的:为什么您采取 IO行 Action 为论据?这意味着allEvents在执行任何自己的工作之前,它本身需要执行该操作以首先获取 URL。这可能有其自身的副作用,并且对于不同的调用会给出不同的结果,您想要吗?

我想不是,所以确实应该是

allEvents :: Maybe [Url] -> IO ()

现在你从一个简单的 Maybe 开始值,您可以轻松地对其进行模式匹配:

allEvents Nothing = ?  -- perhaps simply `return ()`
allEvents (Just urls) = mapM_ doThings urls

要在程序中使用它,您需要将 url 获取单一地绑定(bind)到事件执行:

main :: IO ()
main = do
urlq <- allUrls
allEvents urlq

...或简称allUrls >>= allEvents .

关于haskell - haskell : how to force evaluation of functions and write to a file sequentially?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55759120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com