Examples/Random list
From HaskellWiki
(Difference between revisions)
Revision as of 01:27, 8 September 2007. > unpick :: [a] -> IO [a] > unpick [] = undefined > unpick [x] = do return [] > unpick (x:xs) = do zs <- unpick' [] [x] xs 2 > return (reverse zs) > > unpick' :: (Num p, Random p) => [t] -> [t] -> [t] -> p -> IO [t] > unpick' curr orig [] _ > = do return curr > unpick' curr orig (next:rest) prob > = do r <- getStdRandom (randomR (1,prob)) > let curr' = if r == 1 then orig else (next:curr) > unpick' curr' (next:orig) rest (prob+1)" a lazy thunk. The "start" list parameter to helper is a suffix of "whole" that has the current candidate for deletion as its head. "oldIndex" is the index of the current candidate for deletion in the "whole" list. "here" is a suffix of "whole" with the "index" element of whole as its head. The" but: > Use "removeOne'" to demonstrate when random decisions to drop elements are made. This also demonstrates that removeOne is lazy, appendSome increases as the list is processed. . ] If I use ":m + Data.List" then I can demonstrate how fair the removal is: *Main Data.List> sequence (replicate 1000 $ getStdRandom (removeOne [1..4])) >>= return . map length . group . sort [241,255,239,265] where a perfect balance would be [250,250,250,250]