Why not just construct a list of the functions, and randomly select an element from the list?

Tom

On May 20, 2012 5:14 AM, "Ertugrul Söylemez" <es@ertes.de> wrote:
Stuart Hungerford <stuart.hungerford@gmail.com> wrote:

> 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:
>
> [...]
>
> I'd like to choose and run one of these functions randomly at run
> time. [...]

Again the lookup approach seems most reasonable.  The cleanest way is to
define a simple name type for your functions:

   data FuncIx = FuncA | FuncB deriving (Ord)

   instance Random FuncIx where
       ...

   funcA :: A -> B
   funcB :: A -> B

   funcs :: Map FuncIx (A -> B)
   funcs = M.fromList (zip [FuncA, FuncB] [funcA, funcB])

If you want to go for maximum speed instead:

   import qualified Data.Vector as V

   type FuncIx = Int

   ...

   funcs :: V.Vector (A -> B)
   funcs = V.fromList [funcA, funcB]

   randFunc :: (RandomGen g) => g -> (A -> B, g)
   randFunc = first (funcs V.!) . randomR (0, 1)


Greets,
Ertugrul

--
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/

_______________________________________________
Beginners mailing list
Beginners@haskell.org
http://www.haskell.org/mailman/listinfo/beginners