开发者

How Do I lazily load DataTypes other than Lists in Haskell

开发者 https://www.devze.com 2023-04-08 23:02 出处:网络
I\'m starting to understand the power of Haskell and how lazy loading can be exploited in ways such as

I'm starting to understand the power of Haskell and how lazy loading can be exploited in ways such as

main = do
  s <- getContents
  let r = map processIt (lines s)
  putStr (unlines r)

But the trouble i'm having is extending this kind of "Say what开发者_如何学Cs in the data structure up front but get it when you need it" functionality for other datatypes.

For instance I have a graph type.

type Key = String
data Node = Node { key :: Key, links :: [Node] }

I want to write pure code that acts on this graph (Strait forward searching algorithms) no matter how it is built but I want the Nodes to lazily fill themselves when I get to them.

I think I need a way to specify up front what is in the graph and how to fill it (Some sort of recursive definition) but I'm having trouble seeing how. Something like

loadGraph :: Key -> Node
loadGraph k =
  let (key,edges) = getNodeAndEdgesFromInternetOrDatabase k in
  Node key (map loadGraph edges)

I feel like this is close but I'm not quite sure how to do it. Help and Tips would be appreciated. (especially things like the type of getNodeAndEdgesFromInternetOrDatabase)


Lazy IO is generally implemented using unsafeInterleaveIO, which delays the side effects of an IO action until its result is demanded.

For your example, it would go something like this.

loadGraph :: Key -> IO Node
loadGraph k = unsafeInterleaveIO $ do
  (key, edges) <- getNodeAndEdgesFromInternetOrDatabase k
  edges' <- mapM loadGraph edges
  return (Node key edges')

Since unsafeInterleaveIO is wrapping every call to loadGraph, this will only load that subgraph when you try evaluating it.

Lazy IO is frowned upon by some, as it makes it difficult to reason about the order in which the side effects happen. However, I think for your application it might be suitable, as long as you're careful in how you implement getNodeAndEdgesFromInternetOrDatabase.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号