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

Tom Murphy amindfv at gmail.com
Sun May 20 21:45:01 CEST 2012


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 at ertes.de> wrote:

> Stuart Hungerford <stuart.hungerford at 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 at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120520/6e7faed9/attachment.htm>


More information about the Beginners mailing list