在大多数情况下,下面的(value, index) = maximumBy (comparing fst) (zip list [0..])代码工作得很好,但是,在领带的情况下,它返回最接近尾部的索引,这与我想要的正好相反。也就是说,如果列表是xs = [2,7,3,7],我希望它返回(7,1)而不是(7,3)。有什么简单的方法吗,还是我需要完全重写它?
发布于 2020-10-24 11:08:47
这是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)发布于 2020-10-24 12:13:40
有什么简单的方法吗?还是我需要完全重写它?
如果坚持重用库maximumBy函数,可以这样做:用更合适的方法将fst参数替换为comparing。
例如,否定指数有相反的比较结果。
λ>
λ> 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)
λ> https://stackoverflow.com/questions/64511633
复制相似问题