0

试图在haskell中实现qwerty距离函数。作为其中的一部分,我想出了一个函数的需求,它将返回定义结构(向量、列表、数组?)中特定元素的 i,j 索引。我被困住了。

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

2 回答 2

0

这是将索引与列表元素相关联的任务。通常这很容易做到zip [0..] xs。因此,首先将索引与每个字符串关联,然后将索引与字符串中的每个字符关联。

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

或者,如果您不关心 elemIndex 查找的重复线性成本:

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
于 2013-09-20T12:25:26.423 回答
0

您可以尝试以下方法:

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
于 2013-09-20T12:18:06.513 回答