【问题标题】:Get the index of multiples elements in a haskell list获取haskell列表中多个元素的索引
【发布时间】:2016-03-05 18:13:50
【问题描述】:

我有一个类似[B,B,N,B,N] 的列表,我想检索N 的所有索引。所以,在这个例子中,它将是[2,4]

我真的不知道该怎么做...我尝试使用 elemIndex 但实际上我认为在我的情况下这是不允许的,因为这就是练习的全部意义所在。

我现在这样做了,但我知道它不起作用:

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

【问题讨论】:

    标签: list haskell indexing


    【解决方案1】:

    您的源代码存在一些问题:最重要的是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:我们的“cursor”所在的索引。我们可以使用累加器,让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
    

    【讨论】:

    • 非常感谢,我有使用蓄能器的想法,但我不知道怎么做!
    【解决方案2】:

    您可以使用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]
    

    但是,这只是来自Data.ListelemIndices

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-17
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多