Haskell如何从两个INT列表中返回INT列表
如果list1 = [14,24,1,2,11,7,23,8,12,22,22,22,20,15,19,19,4,9,10,18,18,17,3,3,13 ,16,5,6,25]
, 和list2 = [14,14,24,24,1,1,2,2]
我如何返回的int列表[0,0,1,1,1,2,2,3,3]
我已经使用了该函数
elemIndex' :: Eq a => a -> [a] -> Int
elemIndex' x = fromMaybe (-1) . elemIndex x
,并且为第一个函数提供了结果 0
从列表1获取单位数字的索引 但是我想要的是
findIndex :: [Int] -> [Int] -> [Int]
将输入两个int列表并返回键列表中的索引值基础 我如何递归获取一个列表的索引或使用任何导入功能,例如MAP。
if list1 = [14,24,1,2,11,7,23,8,12,22,20,0,15,19,4,9,10,21,18,17,3,13,16,5,6,25]
,
and list2 = [14,14,24,24,1,1,2,2]
How could I return a int list which is [0,0,1,1,2,2,3,3]
I have used the function
elemIndex' :: Eq a => a -> [a] -> Int
elemIndex' x = fromMaybe (-1) . elemIndex x
and the result for this for the first one0
to get the index from list 1 for a single digit
But what I want is
findIndex :: [Int] -> [Int] -> [Int]
That would input two int list and return the index value base on the key list
How could I recursively get the index for one list or using any import function, such as map.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在解决问题方面做得很好。您已经认识到,您对第二个列表的每个元素的每个元素都做同样的事情,并且已经写了一个函数来捕获该行为。
现在,您需要获取此功能,并将其应用于另一个列表的每个元素,将结果收集到新列表中。也就是说,您想要看起来像的东西
,我们可以搜索 hoogle ,并确切找到该功能:
>代码>地图获取功能和列表,并将其应用于每个元素。您有一个函数(
Elemindex'
,带有适当的部分应用程序),并且您的示例中有一个列表(list2
)。因此,让我们把它放在一起。Haskell中有很多流函数,例如
MAP < / code>,并且知道 /弄清楚在给定情况下使用哪种功能。如果您有疑问,请记住,您可以使用Hoogle来搜索一种类型,也可以简单地做任何要递归做的事情(如果您不知道
MAP
,则可以自己写一些递归),随着时间的流逝,您会掌握它。祝您在Haskell努力中祝您好运!You've done a very good job of breaking the problem down. You've already recognized that you're doing the same thing for each element of the second list, and you've written a function to capture that behavior.
Now you want to take this function and apply it to each element of another list, collecting the results into a new list. That is, you want something that looks like
And we can search Hoogle and find exactly that function:
map
map
takes a function and a list and applies it to each element. You've got a function (elemIndex'
, with appropriate partial application), and you've got a list (list2
in your example). So let's put it together.There are lots of streaming functions in Haskell like
map
, and knowing / figuring out which one to use in a given situation comes with practice. If you're ever in doubt, remember that you can use Hoogle to search for a type or you can simply do whatever you're trying to do recursively (if you didn't knowmap
existed, you could write it yourself with a bit of recursion), and you'll get the hang of it over time. Good luck in your Haskell endeavors!作为@silviomayolo答案的替代方法,您可以使用
MAP
数据结构。我们在list1
中的每个值的索引中zip
,然后将其转换为映射,然后在list2
中对每个值进行查找。As an alternative to the answer by @SilvioMayolo, you could use a
Map
data structure. Wezip
in the indexes for each value inlist1
and then turn that into a map, then just do a lookup for each value inlist2
.