2016-03-05 83 views
0

我有一個像[B,B,N,B,N]這樣的列表,我想檢索N的所有索引。所以,在這個例子中它將是[2,4]得到一個haskell列表中的倍數元素的索引

我真的不知道該怎麼做......我試過elemIndex,但實際上我不認爲這對我來說是允許的,因爲這就是練習的重點。

我這樣做,現在,但我知道,這是行不通的:

indice :: [Case] -> [Int] 
indice [] = [0] 
indice (x:xs) 
    | x == N = [1 + head(indice(xs))] ++ indice(xs) 
    | x == B = [1] 

回答

3

的是與你的源代碼中的一些問題:最重要的是,B情況和空列表生成與物品清單,以及:

indice :: [Case] -> [Int] 
indice [] = [0] -- <- list with elements? 
indice (x:xs) 
    | x == N = [1 + head(indice(xs))] ++ indice(xs) 
    | x == B = [1] -- <- list with elements? 

不過,我認爲這種情況下,你最好使用蓄電池:你在遞歸調用更新的變量。在這種情況下的累加器是i:我們的「光標」所在的索引。我們可以用一個蓄電池,通過使indice調用一個輔助函數:

indice :: [Case] -> [Int] 
indice = helper 0 
    where helper --... 

現在我們仍然需要定義我們的helper功能。

此外有三種情況,我們必須照顧:

  • 我們到達了列表的末尾,在這種情況下,我們返回一個空列表,以及:

    helper _ [] = [] 
    
  • 光標位於N,我們「發出」索引並進行遞歸調用更新索引:

    helper i (N:xs) = i : helper (i+1) xs 
    
  • 光標位於另一個角色,我們只是向前移動光標,並更新索引:

    helper i (_:xs) = helper (i+1) xs 
    

全部放在一起,我們得到:

indice :: [Case] -> [Int] 
indice = helper 0 
    where helper _ [] = [] 
      helper i (N:xs) = i : helper (i+1) xs 
      helper i (_:xs) = helper (i+1) xs 
+1

非常感謝,我的想法是使用累加器但我不知道該怎麼做! – pioupiou1211

3

你可以使用zip使用其索引標記每個元素,篩選符合條件的元素,然後剝離這些值,只留下索引:

indexesOf :: Eq a => a -> [a] -> [Int] 
indexesOf v = map fst . filter ((== v) . snd) . zip [0..] 

因此,假設由NB居住的類型是Eq的情況下,你可以這樣做:

indexesOf N [B,B,N,B,N] 

,並得到了答案:

[2,4] 

但是,這僅僅是elemIndices from Data.List

相關問題