HaskellWiki

Haskell | Wiki community | Recent changes
Random page | Special pages

 

Not logged in
Log in | Help

Haskell Quiz/Grid Folding/Solution Dolio

< Haskell Quiz | Grid Folding

Categories: Haskell Quiz solutions


The basis for my solution is simple. Consider each square to be a single-element list initially. Then, a row of such squares is a list of such lists. An entire grid is then a list of those lists.

When folding horizontally, one splits each row, reverses the half to go on top (as well as its elements, since they'll be flipped), and zips the two halves together by appending corresponding elements. This results in a top-first list of the stacked squares.

When folding vertically, one splits the grid in half, reverses the half to go on top, and zips the two grid halves together. The function that combines corresponding rows is yet another zip that appends corresponding elements (again, reversing the ones on top).

module Main where
import Control.Monad.Reader
import Data.Char
import System
 
grid n = break . map return $ [1..(n*n)]
 where break [] = []
       break l  = let (h,t) = splitAt n l in h : break t
 
fold 'T' = folder vzipper
fold 'B' = folder (flip vzipper)
fold 'L' = map (folder hzipper)
fold 'R' = map (folder $ flip hzipper)
fold _   = error "Unrecognized letter."
 
vzipper = zipWith (zipWith $ (++) . reverse) . reverse
hzipper = zipWith (++) . (map reverse . reverse)
 
folder z = uncurry z . ap (flip splitAt) (flip div 2 . length)
 
pretty = unlines . map unwords . map (map show)
 
output s = if filter (not . isSpace) s == []
              then error "Invalid folding scheme"
              else putStr s
 
main = do [n, s] <- getArgs
          output . pretty . foldl (flip fold) (grid $ read n) $ s

Retrieved from "http://www.haskell.org/haskellwiki/Haskell_Quiz/Grid_Folding/Solution_Dolio"

This page has been accessed 583 times. This page was last modified 10:49, 13 January 2007. Recent content is available under a simple permissive license.