Search code examples
haskelldistanceqwerty

Haskell find 2d index for qwerty distance


Trying to implement qwerty distance function in haskell. As a part of this, I came up with a need for a function, that would return an i,j index of specific element in a defined structure (vector, list, array?). And I'm stuck.

import qualified Data.Vector as V
qwerty = V.fromList $ map V.fromList
        [ "qwertyuiop", "asdfghjkl;'", "zxcvbnm,./" ]

Solution

  • This is a task of associating a index with the list elements. Usually this is easy to do with zip [0..] xs. So, first associate a index with each string, then associate a index with each character in the string.

    import qualified Data.Map as M
    qwmap = M.fromList $ concatMap f $ zip [0..] qwerty where
       qwerty = ["qwertyuiop[]", "asddfghjkl;'#", "zxcvbnm,./"]
       f (i,cs) = map (\(j,c) -> (c, (i,j))) $ zip [0..] cs
    

    Alternatively, if you don't care about repeating linear cost of elemIndex lookup:

    import Data.List
    qp a = foldr f Nothing $ zip [0..] qwerty where
       qwerty = ["qwertyuiop[]", "asddfghjkl;'#", "zxcvbnm,./"]
       f (p,xs) n = maybe n (Just . (p,)) $ elemIndex a xs