[Haskell-beginners] Searching for word in 2D array

Ozgur Akgun ozgurakgun at gmail.com
Fri Mar 23 01:21:55 CET 2012


Hi,

import Data.List
import qualified Data.Set as S

rows :: Ord a => [[a]] -> S.Set [a]
rows = S.fromList

cols :: Ord a => [[a]] -> S.Set [a]
cols = S.fromList . transpose

diagonals :: Ord a => [[a]] -> S.Set [a]
diagonals []  = S.empty
diagonals xss = S.union
    ( S.fromList $ transpose (zipWith drop [0..] xss) )
    ( diagonals (map init (tail xss)) )

allWords :: Ord a => [[a]] -> S.Set [a]
allWords xss = S.unions
    [ rows xss
    , cols xss
    , diagonals xss
    , diagonals (map reverse xss)
    ]

Now you can do all sorts of things, since you have the set of all words at
hand.

The function you originally wanted, checking the existence of a word can be
the following:

search :: Ord a => [a] -> [[a]] -> Bool
search word xss = not $ null [ () | xs <- S.toList (allWords xss), word
`isPrefixOf` xs ]

But I suppose a function which removes the found word from the set could be
more useful.

Please ask if you have any questions about the above code, I can try to
elaborate.

Hope this helps,
Ozgur
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120323/44a5debe/attachment.htm>


More information about the Beginners mailing list