Skip to content

Instantly share code, notes, and snippets.

@Agnishom
Last active June 30, 2018 15:01
Show Gist options
  • Select an option

  • Save Agnishom/3733841017a84627814285b53b1fa4a7 to your computer and use it in GitHub Desktop.

Select an option

Save Agnishom/3733841017a84627814285b53b1fa4a7 to your computer and use it in GitHub Desktop.
List Monad as Non-deterministic computation
import Control.Monad.Random
arbitrarySet :: Monad m => m Bool -> [a] -> m [a]
arbitrarySet getBool = flip foldr (return []) $ \x ls -> do
t <- getBool
l <- ls
if t
then return (x:l)
else return l
randomSet :: [a] -> IO [a]
randomSet = arbitrarySet (getRandom :: IO Bool)
powerset :: [a] -> [[a]]
powerset = arbitrarySet [True, False]
{-
Computing the powerset is equivalent to non-deterministically computing a subset.
How do you non-deterministically compute a subset?
1. Start with the empty set : `return []`
2. For each element in the given set, : `flip foldr`
3. Nondeterministically choose either True or False. : `t <- getBool`
4. If you : `if t`
5. chose True, then add the element : `then return (x:l)`
6. otherwise, do not : `else return l`
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment