5

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?

Lanbo
  • 13,437
  • 14
  • 67
  • 141

1 Answers1

6

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.

augustss
  • 22,266
  • 5
  • 52
  • 91
  • So you mean, like, in a relational database? – Lanbo Jun 26 '11 at 12:44
  • 2
    I mean that each node must have some unique name. Maybe refName is unique? Then when you output a node you remember it's name, so the if you ever try to output that node again you instead output a (back) reference to it. It's more involved, but necessary to handle cycles. – augustss Jun 26 '11 at 12:51