Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8864467
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T16:14:53+00:00 2026-06-14T16:14:53+00:00

Consider the following abbreviated code from this excellent blog post : import System.Random (Random,

  • 0

Consider the following abbreviated code from this excellent blog post:

import System.Random (Random, randomRIO)

newtype Stream m a = Stream { runStream :: m (Maybe (NonEmptyStream m a)) }
type NonEmptyStream m a = (a, Stream m a)

empty :: (Monad m) => Stream m a
empty = Stream $ return Nothing

cons :: (Monad m) => a -> Stream m a -> Stream m a
cons a s = Stream $ return (Just (a, s))

fromList :: (Monad m) => [a] -> NonEmptyStream m a
fromList (x:xs) = (x, foldr cons empty xs)

Not too bad thus far – a monadic, recursive data structure and a way to build one from a list.

Now consider this function that chooses a (uniformly) random element from a stream, using constant memory:

select :: NonEmptyStream IO a -> IO a
select (a, s) = select' (return a) 1 s where
  select' :: IO a -> Int -> Stream IO a -> IO a
  select' a n s = do
    next <- runStream s
    case next of 
      Nothing -> a
      Just (a', s') -> select' someA (n + 1) s' where
        someA = do i <- randomRIO (0, n) 
                   case i of 0 -> return a'
                             _ -> a

I’m not grasping the mysterious cyclic well of infinity that’s going on in the last four lines; the result a' depends on a recursion on someA, which itself could depend on a', but not necessarily.

I get the vibe that the recursive worker is somehow ‘accumulating’ potential values in the IO a accumulator, but I obviously can’t reason about it well enough.

Could anyone provide an explanation as to how this function produces the behaviour that it does?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T16:14:54+00:00Added an answer on June 14, 2026 at 4:14 pm

    That code doesn’t actually run in constant space, as it composes a bigger and bigger IO a action which delays all the random choices until it’s reached the end of the stream. Only when we reach the Nothing -> a case does the action in a actually get run.

    For example, try running it on an infinite, constant space stream made by this function:

    repeat' :: a -> NonEmptyStream IO a
    repeat' x = let xs = (x, Stream $ return (Just xs)) in xs
    

    Obviously, running select on this stream won’t terminate, but you should see the memory usage going up as it allocates a lot of thunks for the delayed actions.

    Here’s a slightly re-written version of the code which does the choices as it goes along, so it runs in constant space and should hopefully be more clear as well. Note that I’ve replaced the IO a argument with a plain a which makes it clear that there are no delayed actions being built up here.

    select :: NonEmptyStream IO a -> IO a
    select (x, xs) = select' x 1 xs where
      select' :: a -> Int -> Stream IO a -> IO a
      select' current n xs = do
        next <- runStream xs
        case next of 
          Nothing       -> return current
          Just (x, xs') -> do
            i <- randomRIO (0, n)                         -- (1)
            case i of                                     
              0 -> select' x       (n+1) xs'              -- (2)
              _ -> select' current (n+1) xs'              -- (3)
    

    As the name implies, current stores the currently selected value at each step. Once we’ve extracted the next item from the stream, we (1) pick a random number and use this to decide whether to (2) replace our selection with the new item or (3) keep our current selection before recursing on the rest of the stream.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider following code: public sealed class Program { public static void Main() { System.Console.WriteLine(Hi);
Consider following piece of code: declare @var bit = 0 select * from tableA
Consider following code: Dim S1 As String = a 'this is the string in
Consider following code: My problem is: 1) I can't seem to cast the errors
consider following: 1st APPROACH: public void f3() { f2(); f1(); } and this ...
Consider following SWT code example: http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet151.java?view=co How can I separate the inline defined class?
Consider following code for an android app; private String GetDistance(String src, String dest) {
Let's consider following html code: <p> Some text followed by <span>a span element</span> and
Consider following tables: How to skip and take groups from the table? Tried using
Consider following code: main.cpp: #include <iostream> typedef void ( * fncptr)(void); extern void externalfunc(void);

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.