Hacker News new | ask | show | jobs
by psykotic 5264 days ago
Hey, sorry for the late reply.

It seems pretty obvious to me, so I'm not sure what is confusing you.

    class Monad m => ChoiceMonad m where
        choice :: [a] -> m a
For the list monad, choice is just the identity function. For the probability monad, choice picks a random element from the list. (Ideally choice would take a random access structure like a set as its argument, but I'm doing it the simplest way here.)

To implement shuffle, you more or less just transliterate the Python code as you'd expect.

Before you tackle this, make you sure completely understand how the same situation plays out for the simpler case of subsets:

    subset        :: ChoiceMonad m => [a] -> m [a]
    subset []     = return []
    subset (x:xs) = do b <- choice [True, False]
                       xs' <- subset xs
                       return (if b then x:xs' else xs')
Over the list monad, this generates a list of all subsets. Over the probability monad, it generates a random subset.
1 comments

Thank you, now I see. Here's my version:

    shuffle :: (ChoiceMonad m, Eq a) => [a] -> m [a]
    shuffle [] = return []
    shuffle elems = do 
      x <- choice elems
      xs <- shuffle (x `delete` elems)
      return (x:xs)