Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List Haskell:如何显示列表中的所有元素和索引对?_List_Haskell_Indexing - Fatal编程技术网

List Haskell:如何显示列表中的所有元素和索引对?

List Haskell:如何显示列表中的所有元素和索引对?,list,haskell,indexing,List,Haskell,Indexing,需要获得下一个输入和输出: pospair [1, 3, 9, 2, 5, 7, 1, 11] [1, 9, 5, 1] posimpair [1, 3, 9, 2, 5, 7, 1, 11] [3, 2, 7, 11] 这是获取指定索引上的元素的方法: show_in_index::Ord a=>[a]->Int->a show_in_index l n = l!!n 它显示了如下结果: *Main> show_in_index

需要获得下一个输入和输出:

pospair [1, 3, 9, 2, 5, 7, 1, 11]
        [1, 9, 5, 1]

posimpair [1, 3, 9, 2, 5, 7, 1, 11]
          [3, 2, 7, 11]
这是获取指定索引上的元素的方法:

show_in_index::Ord a=>[a]->Int->a
show_in_index l n = l!!n
它显示了如下结果:

*Main> show_in_index [1,4,2,7,9] 3
7

您可以映射用于索引的函数

对于pospair,需要进行以下工作:

map ([1, 3, 9, 2, 5, 7, 1, 11] !! ) [0,2..length [1, 3, 9, 2, 5, 7, 1, 11]-1]
对于posdigment,我们只需要更改第二个列表,即保存索引编号的列表,以前我们有一系列对,现在我们需要一系列的digment,因此,不是0,2,。。直到列表的长度-1,我们必须用1,3来做,直到列表的长度-1

map ([1, 3, 9, 2, 5, 7, 1, 11] !! ) [1,3..length [1, 3, 9, 2, 5, 7, 1, 11]-1]
一般的实施是

pospairs=map(list!!)[0,2..length list-1]

posdisbids=map(list!!)[1,3..length list-1]


我测试了您的示例,效果良好。

最简单的方法是使用递归:

pospair :: [a] -> [a]
pospair xs = aux xs [] True
    where
      aux [] acc _ = acc
      aux (y:ys) acc True = aux ys (acc ++ [y]) False
      aux (y:ys) acc False = aux ys acc True

注意我如何使用
True
False
值来跟踪要消除的值。如果为False,则不在
acc
(累加器)中包含该值。如果它是
真的
,我会包含该值。使用相同的想法,您可以实现
post

您能告诉我们您到目前为止做了哪些尝试吗?到目前为止,我只知道这是一种在特定位置查找元素的方法,但我不知道如何在指定位置或成对位置显示所有元素:
show_in_index::Ord a=>[a]->Int->a show_in_index l n=l!!n