Haskell find 2d index for qwerty distance

0

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,./" ]

Антон Колесник

Posted 2013-09-20T11:55:02.267

Reputation: 3

Answers

0

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

Sassa NF

Posted 2013-09-20T11:55:02.267

Reputation: 4 339

0

You can try something like:

import qualified Data.Vector as V

qwerty = V.fromList $ map V.fromList
        [ "qwertyuiop", "asdfghjkl;'", "zxcvbnm,./" ]

findElement :: Char -> Maybe (Int,Int)
findElement c = f $ V.findIndex (V.elem c) qwerty where
  f (Just i) = (,) i `fmap` (V.elemIndex c $ qwerty V.! i)
  f Nothing = Nothing

Ankur

Posted 2013-09-20T11:55:02.267

Reputation: 29 953