[Haskell-cafe] Releasing head of lazy ByteString

Antoine Latter aslatter at gmail.com
Sun Feb 20 17:04:17 CET 2011

On Sun, Feb 20, 2011 at 9:38 AM, tsuraan <tsuraan at gmail.com> wrote:
> I have a streaming network protocol where each message in the stream
> is prefixed by a 64-bit message length marker.  Lazy ByteStrings seem
> to be an elegant way to wrap network communications, so I'm using
> them.  I have one concern though: how can I prevent my program from
> hanging on to the beginning of the stream?  My code looks roughly like
> this:
> lazy <- getContents clientSock
> let (lenBS, rest1) = splitAt 8 lazy
> let length = runGet getWord64be lenBS
> let (msg, rest2) = splitAt (fromIntegral length) rest1
> -- process msg
> The program never uses that initial "lazy" again, but it's there, and
> it's been assigned, so I assume that reference to the head of the
> stream will always be around, and thus always consuming memory.  Is
> there a way to indicate to haskell that I want to "forget" about that
> assignment, so the runtime doesn't need to keep the stream around?  In
> this case, I think I could do the stream processing in a
> tail-recursive loop, and thus lose the previous references to the
> stream, but is there a more specific way to tell haskell that I'm done
> with some data?

One easy trick is to put the rest of the function body in a separate
top-level function, so that the 'lazy' variable is no longer in scope.


> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

More information about the Haskell-Cafe mailing list