randomized-zines/recombiner1.hs

45 lines
1.5 KiB
Haskell

import System.IO
import System.Random
-- we're starting with a file where sections are separated by
-- begin-section
-- end-section
collectSections :: [String] -> [String]
collectSections strs = collectSections' strs []
-- if we don't close an accumulation we just throw it away
-- we also don't check for beginning a new section inside a section
collectSections' [] accum = []
collectSections' (x:xs) accum | x == "begin-section" = collectSections' xs []
| x == "end-section" = (unlines $ reverse accum) : collectSections' xs []
| otherwise = collectSections' xs (x : accum)
parseFile :: String -> [String]
parseFile = collectSections . lines
-- this function shouldn't just split the lists at the point
-- but grab the element at that point
-- [0,1,2,4]
-- this function is only defined for 1
splitAtElem n xs = let (xl,xr) = splitAt n xs in (xl, head xr, tail xr)
randomizeSections :: (RandomGen g) => g -> [String] -> [String]
randomizeSections g [] = []
randomizeSections g [x] = [x]
randomizeSections g xs = let (n,g') = uniformR (0,length xs-1) g --
(l,x,r) = splitAtElem n xs
in x : randomizeSections g' (l ++ r)
-- small testing main function, to replace
main :: IO ()
main = do
contents <- readFile "test.txt"
g <- initStdGen
let parsed = parseFile contents
putStrLn "Initial"
putStrLn $ unlines $ parsed
putStrLn "Randomized"
putStrLn $ unlines $ randomizeSections g $ parsed