开发者

How to store recursive datatype with Data.Binary

开发者 https://www.devze.com 2023-03-15 16:51 出处:网络
Data.Binary is great. There is just one question I have. Let\'s imagine I\'ve got a datatype like this:

Data.Binary is great. There is just one question I have. Let's imagine I've got a datatype like this:

import Data.Binary

data Ref = Ref {
    refName :: String,
    refRefs :: [(String, Ref)]
}

instance Binary Ref where
    put a = put (refName a) >> put (refRefs a)
    get = liftM2 Ref get get

It's easily to see that this is a recursive datatype,开发者_开发技巧 which works because Haskell is lazy. Since Haskell as a language uses neither references nor pointers, but presents the data as-is, I am not sure how this is going to be saved. I have the strong indication that this naive reproach will lead to an infinite bytestring...

So how can this type be safely saved?


If your data has no cycles you'll be fine. But a cycle, like

r = Ref "a" [("b", r)]

is indeed going to generate an infinite result. The only way around this is for you to give unique labels to all nodes and use those to avoid cycles when converting to binary.

0

精彩评论

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