尝试在haskell中实现qwerty距离函数。 作为其中的一部分,我想出了一个函数,它将在定义的结构(向量,列表,数组?)中返回特定元素的i,j索引。 我被卡住了。
import qualified Data.Vector as V
qwerty = V.fromList $ map V.fromList
[ "qwertyuiop", "asdfghjkl;'", "zxcvbnm,./" ]
答案 0 :(得分: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
答案 1 :(得分: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