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

Ertugrul Söylemez es at ertes.de
Sun May 20 11:13:22 CEST 2012


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/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120520/0fef612d/attachment.pgp>


More information about the Beginners mailing list