Search code examples
haskelldoctesthaddock

getting and testing a random item in a list in Haskell


Lets say there is a list of all possible things

all3PStrategies :: [Strategy3P]
all3PStrategies = [strategyA, strategyB, strategyC, strategyD]  //could be longer, maybe even infinite, but this is good enough for demonstrating

Now we have another function that takes an integer N and two strategies, and uses the first strategy for N times, and then uses the second strategy for N times and continues to repeat for as long as needed.
What happens if the N is 0, I want to return a random strategy, since it breaks the purpose of the function, but it must ultimatley apply a particular strategy.

rotatingStrategy [] [] _ = chooseRandom all3PStrategies
rotatingStrategy strategy3P1 strategy3P2 N =
  | … // other code for what really happens

So I am trying to get a rondom strategy from the list. I Think this will do it:

chooseRandom :: [a] -> RVar a

But how do I test it using Haddock/doctest?

--  >>> chooseRandom all3PStrategies
--      // What goes here since I cant gurauntee what will be returned...?

I think random functions kind of goes against the Haskell idea of functional, but I also am likely mistaken. In imperative languages the random function uses various parameters (like Time in Java) to determine the random number, so can't I just plug in a/the particular parameters to ensure which random number I will get?


Solution

  • If you do this: chooseRandom :: [a] -> RVar a, then you won't be able to use IO. You need to be able to include the IO monad throughout the type declaration, including the test cases.

    Said more plainly, as soon as you use the IO monad, all return types must include the type of the IO monad, which is not likely to be included in the list that you want returned, unless you edit the structure of the list to accommodate items that have the IO Type included.