[Haskell-beginners] Choosing a function randomly...

Stuart Hungerford stuart.hungerford at gmail.com
Sun May 20 08:42:07 CEST 2012


Hi,

This is kind-of related to my earlier question on looking up functions
by name.  Suppose I have a module with a number of functions with the
same signature:

scale :: Int -> Int -> Int

scale s x = s * x

add :: Int -> Int -> Int

add a x = a + x

...

I'd like to choose and run one of these functions randomly at run
time. I can see I could use some kind of case expression:

op :: Int -> Int -> Int

op p x = case random(1,2) of
   1 -> scale p x
   2 -> add p x

Or some kind of pattern guards:

op p x
  | random(1,2) == 1 = scale p x
  | otherwise  = add p x

Although that method won't work as is for more than two choices.  Are
these methods the most idiomatic way of randomly choosing a function?
 How hard would it be to use the machinery of the QuickCheck library
for this, given it must be doing something similar in test suites?

Thanks,

Stu



More information about the Beginners mailing list