[Haskell-cafe] Memory leak in infinite recursion

David Feuer david.feuer at gmail.com
Wed Jun 20 10:54:32 UTC 2018


On Tue, Jun 19, 2018, 9:54 PM Dr.Koster <drkoster at qq.com> wrote:

> In general infinite monadic recursion will leak, since the tail position
> is always >> or >>= instead of your own recursive function
>

That seems a bit strong. Monadic recursion *can* leak, but it need not. >>=
is typically lazy in its second argument, so it can produce structure
lazily. Consider the free monad, for example:

data Free f a = Pure a | Wrap (f (Free f a))

instance Functor f => Monad (Free f) where
  Pure a >>= f = f a
  Wrap ff >>= f = Wrap $ fmap (>>= f) ff

See how we can produce Wrap without using f? As long as the base functor
isn't too large, this shouldn't leak.

, but under certain situations, e.g. IO without arguments, the compiler
> will figure there's no need to push new stack frame. But anyway it's better
> to checkout yourself rather relying on some weak assumptions.
>
> 发自我的iPhone
>
>
> ------------------ Original ------------------
> *From:* Никита Фуфаев <kitttoran at gmail.com>
> *Date:* Wed,Jun 20,2018 2:37 AM
> *To:* haskell-cafe <haskell-cafe at haskell.org>
> *Subject:* Re: [Haskell-cafe] Memory leak in infinite recursion
>
> Hello everyone
>
> In C you can't implement main loop with recursion like
> void mainLoop() {
>   doSomething();
>   mainLoop();
> }
> because without optimisations stack will overflow.
> In haskell it's common to write
> mainLoop = doSomething >> mainLoop, and it doesn't leak memory because of
> haskell's evaluation model.
> Does memory leak or argument stack overflow happen in this case?
> mainLoop = doSomething >> mainLoop >> exit ExitSuccess
> What about this case?
> mainLoopModeA = do
>   doSomething
>   when condition mainLoopModeB
>   mainLoopModeA
> mainLoopModeB = do
>   doSomethingElse
>   when anotherCondition mainLoopModeA
>   mainLoopModeB
>
> or this case?
> mainLoopModeA = do
>   doSomething
>   if condition
>     then mainLoopModeB
>     else mainLoopModeA
> mainLoopModeB = do
>   doSomethingElse
>   if anotherCondition
>     then mainLoopModeA
>     else mainLoopModeB
>
> --
> Nikita Fufaev
> _______________________________________________
> Haskell-Cafe mailing list
> To (un)subscribe, modify options or view archives go to:
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
> Only members subscribed via the mailman list are allowed to post.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20180620/dedb820f/attachment.html>


More information about the Haskell-Cafe mailing list