Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.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 列表中的Max和它在Haskell中的索引——对于tie,我需要最靠近头部的元素_List_Haskell_Indexing - Fatal编程技术网

List 列表中的Max和它在Haskell中的索引——对于tie,我需要最靠近头部的元素

List 列表中的Max和它在Haskell中的索引——对于tie,我需要最靠近头部的元素,list,haskell,indexing,List,Haskell,Indexing,我的代码如下 (值、索引)=maximumBy(比较fst)(邮政编码列表[0..]) 在大多数情况下工作正常,但是,在平局的情况下,它返回最靠近尾部的索引,这与我想要的相反。 也就是说,如果列表是xs=[2,7,3,7],我希望它返回(7,1),而不是(7,3)。有没有一个简单的方法来完成它,或者我需要完全重写它?这是maximumBy maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a maxi

我的代码如下
(值、索引)=maximumBy(比较fst)(邮政编码列表[0..])
在大多数情况下工作正常,但是,在平局的情况下,它返回最靠近尾部的索引,这与我想要的相反。
也就是说,如果列表是
xs=[2,7,3,7]
,我希望它返回
(7,1)
,而不是
(7,3)
。有没有一个简单的方法来完成它,或者我需要完全重写它?

这是
maximumBy

maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
maximumBy cmp = foldl1 max'
  where max' x y = case cmp x y of
                        GT -> x
                        _  -> y
根据定义,它返回最右边的max元素。 我想,获取最左边的max元素最简单的方法是定义自己的
maximumBy'
如下

maximumBy' cmp = fold1 max'
  where max' x y = case cmp x y of
                        LT -> y
                        _  -> x
所有其他方法都以某种方式重新定义了
max
,就像我们在这里所做的那样

这将给你:

> maximumBy' (comparing fst) (zip xs [0..])
> (7,1)
有没有一个简单的方法来完成它,或者我需要完全重写它? 如果坚持重用库
maximumBy
函数,可以这样做:将
fst
参数替换为
比较

例如,对索引求反,使比较结果与之相反

 λ> 
 λ> xs = [2,7,3,7]
 λ> 
 λ> maximumBy  (comparing (\(v,x) -> (v,-x)))  (zip xs [0..])
 (7,1)
 λ> 

如果您熟悉Haskell设施,同样的想法可以用更简洁的方式表达:

 λ> 
 λ> import Control.Arrow
 λ> 
 λ> maximumBy  (comparing (second id))  (zip xs [0..])
 (7,3)
 λ> 
 λ> maximumBy  (comparing (second negate))  (zip xs [0..])
 (7,1)
 λ> 
 λ> maximumBy  (comparing (id *** negate))  (zip xs [0..])
 (7,1)
 λ> 


您的测试当前只是比较fst,因此它完全忽略了索引(
snd
)。您可能希望使用更复杂的测试,这也是一个适当考虑索引的测试。
minimumBy(比较(先下))$zip[1,7,2,7][0..
。或
maximumBy(比较(第二个向下))$…
。虽然这取决于现在删除的Q上的
Ord
@jpmarinier中的索引,但指向指南的是amalloy,而不是我。根据他们的解释,我犯了不可饶恕的罪,我也做出了上述评论。@WillNess-是的,很抱歉造成混乱。我刚刚发现我的错误,就在我脚下,问题被删除了。因此,我没有时间将我的评论转到amalloy。这样的丛林也是如此:-)无论如何,谢谢你找到回到我身边的方法。