簡體   English   中英

獲取Haskell中字符串列表中元素的位置

[英]Get positions of elements in list of strings in Haskell

我的頭銜可能有點偏,我會試着更好地解釋一下我想要實現的目標。

基本上我要說我有一個清單:

["1234x4","253x4",2839",2845"]

現在我想將包含元素5的字符串的所有位置添加到新列表中。 在當前示例中,結果列表將是:

[1,3]

為此我已經為elem做了類似的功能:

myElem [] _ = False
myElem [x] number =
  if (firstCheck x) then if digitToInt(x) == number then True else False else False
myElem (x:xs) number =
if (firstCheck x) then (if digitToInt(x) == number then True else myElem xs number) else myElem xs number

其中firstCheck x檢查checked元素不是'x'或'#'

現在,在我當前的函數中,我獲得了包含元素的第一個元素位置,但是我的頭部仍然在如何獲取完整列表:

findBlock (x:xs) number arv =
  if myElem x number then arv else findBlock xs number arv+1

其中arv為0, number是我正在尋找的數字。

例如輸入:

findBlock ["1234x4","253x4",2839",2845"] 5 0 

結果將是1

任何幫助,將不勝感激。

您想要的函數已經存在於Data.List模塊中,名稱為findIndices 您可以簡單地使用(elem '5')作為謂詞。

http://hackage.haskell.org/package/base-4.8.1.0/docs/Data-List.html#v:findIndices

如果,由於某種原因,你不允許使用內置的,它帶有一個非常漂亮的定義(雖然實際使用的那個有一個更復雜,更有效的一個):

findIndices p xs = [ i | (x,i) <- zip xs [0..], p x]

順便說一句,我通過搜索Hoogle的類型[a] -> (a -> Bool) -> [Int]找到了這個函數,其中(模數參數排序)顯然是函數必須具有的類型。 找出Haskell的最佳方法是考慮它需要的類型並搜索Hoogle或Hayoo的類型。 Hoogle是更好的IMO,因為它在類型上略有模糊匹配; 例如,Hayoo不會通過我給出的類型在這里找到函數,因為它以相反的順序獲取參數。

findIndices的實現,用於教學目的:

findIndices ok list = f list 0 where
  f [] _ = []
  f (x:xs) ix
    | ok x      = ix : f xs (ix+1)
    | otherwise =      f xs (ix+1)

findIndices (elem '5') my_list_o_strings一樣使用它

您正試圖通過列表工作,跟蹤您在列表中的位置。 這樣做最簡單的功能是

mapWithIndex :: (Int -> a -> b) -> [a] -> [b]
mapWithIndex = mwi 0 where
  mwi i _f [] = i `seq` []
  mwi i f (x:xs) = i `seq` f i x : mwi (i+1) f xs

這需要一個函數和一個列表,並將該函數應用於每個索引和元素。 所以

mapWithIndex (\i x -> (i, x)) ['a', 'b', 'c'] =
[(0,'a'), (1,'b'),(2,'c')]

完成后,您可以filter列表以獲得所需的對:

filter (elem '5' . snd)

然后map fst到它上面以獲得索引列表。

更集成的方法是使用foldrWithIndex

foldrWithIndex :: (Int -> a -> b -> b) -> b -> [a] -> b
foldrWithIndex = fis 0 where
  fis i _c n [] = i `seq` n
  fis i c n (x:xs) = i `seq` c i x (fis (i+1) c n xs)

這使您可以一步完成所有操作。

事實證明,您可以使用foldr非常巧妙地實現foldrWithIndex ,這使得它可用於任何Foldable容器:

foldrWithIndex :: (Foldable f, Integral i) =>
  (i -> a -> b -> b) -> b -> f a -> b
foldrWithIndex c n xs = foldr go (`seq` n) xs 0 where
  go x r i = i `seq` c i x (r (i + 1))

無論如何,

findIndices p = foldrWithIndex go [] where
  go i x r | p x = i : r
           | otherwise = r

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM