问题描述
我正在尝试创建一个haskell函数,该函数将列表中某个值出现的所有索引作为列表返回,就像这样
Im trying to create a haskell function where all the indices of an occurence of a value in a list are returned as a list, so like
indices 3 [1,2,3,3,7]
给出[2,3]作为输出.我对Haskell非常陌生,无法找到有用的东西.我尝试使用过滤器,但是我所能做的只是得到[3,3]的列表,而不是实际的索引.如果您能给我一些提示,那就太好了.
gives [2, 3] as output. I am very new to Haskell and couldnt find something useful. I tried using filter, but all i got working is getting a list of [3, 3] but not the actual indices. It would be cool if you could give me a little hint.
推荐答案
这是函数式编程中非常常见的模式,有时称为decorate-process-undecorate.这样的想法是,您希望将一些额外的信息附加到列表中的每个元素上,使用您通常会做的稍稍改动的过滤器版本进行过滤,然后将这些多余的信息去除.
This is a pretty common pattern in functional programming, sometimes called decorate-process-undecorate. The idea is that you want to attach some extra information to each of the elements in your list, filter using a slightly altered version of the filter you would have done normally, then strip that extra information away.
indicies n = undecorate . filter predicate . decorate where
decorate = ...
predicate = ...
undecodate = ...
当尝试对装饰
进行编码时,建议您查看一下 zip
函数:
When trying to code decorate
I suggest taking a look at the function zip
:
zip :: [a] -> [b] -> [(a, b)]
还要考虑其对无限列表的影响,例如 repeat 1
或 [1,3,...]
.尝试对取消装饰
进行编码时,您可能需要 map
:
Consider its effect on infinite lists, too, such as repeat 1
or [1,3,...]
. When trying to code undecorate
you'll likely want to map
:
map :: (a -> b) -> [a] -> [b]
最后,不必担心此过程的效率.用严格的语言来说,decorate-filter-undecorate可能需要遍历该列表的3个遍历.在像Haskell这样的非严格语言中,编译器会自动将3个内部循环合并为一个循环.
Finally, don't worry about the efficiency of this process. In a strict language, decorate-filter-undecorate might require 3 traversals of the list. In a non-strict language like Haskell the compiler will automatically merge the 3 inner loops into a single one.
这篇关于获取值的所有索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!