Haskell中如何用Integer处理运行最小/最大问题(无需非空输入)
在Haskell中用Integer类型处理运行最小/最大值(支持空输入)
方法一:用Maybe类型包装结果
直接用Maybe区分空输入与非空输入的结果:空输入返回Nothing,非空输入返回Just 最小值/最大值。初始化状态设为Nothing,遍历元素时动态确定初始值,完全避开边界值或无穷值的依赖。
示例代码:
import Data.List (foldl') -- 计算运行最小值 runMin :: [Integer] -> Maybe Integer runMin = foldl' updateMin Nothing where updateMin Nothing x = Just x updateMin (Just currentMin) x = Just $ min currentMin x -- 计算运行最大值 runMax :: [Integer] -> Maybe Integer runMax = foldl' updateMax Nothing where updateMax Nothing x = Just x updateMax (Just currentMax) x = Just $ max currentMax x
该方案贴合Haskell惯用模式,无需额外定义类型,空输入的处理自然融入逻辑。
方法二:自定义带无穷值的扩展整数类型
若需明确表示“无穷”状态(比如固定滑动窗口未填满时的初始状态),可自定义包含无穷值的代数数据类型,实现Ord实例后即可像普通整数一样比较:
data ExtendedInteger = Finite Integer | PositiveInfinity | NegativeInfinity deriving (Show, Eq) instance Ord ExtendedInteger where compare PositiveInfinity PositiveInfinity = EQ compare PositiveInfinity _ = GT compare _ PositiveInfinity = LT compare NegativeInfinity NegativeInfinity = EQ compare NegativeInfinity _ = LT compare _ NegativeInfinity = GT compare (Finite a) (Finite b) = compare a b -- 空输入返回PositiveInfinity runMinExt :: [Integer] -> ExtendedInteger runMinExt = foldl' updateMin PositiveInfinity where updateMin current x = min current (Finite x) -- 空输入返回NegativeInfinity runMaxExt :: [Integer] -> ExtendedInteger runMaxExt = foldl' updateMax NegativeInfinity where updateMax current x = max current (Finite x)
此方案适合需要保留“空窗口对应无穷值”语义的场景,滑动窗口问题中未填满的初始状态可直接用无穷值参与后续比较。
方法三:结合foldr的惰性处理(针对全局最值场景)
若仅需计算全局最小/最大值而非逐步骤运行结果,用foldr可实现惰性处理,同时支持空输入:
runMinLazy :: [Integer] -> Maybe Integer runMinLazy [] = Nothing runMinLazy (x:xs) = Just $ foldr min x xs runMaxLazy :: [Integer] -> Maybe Integer runMaxLazy [] = Nothing runMaxLazy (x:xs) = Just $ foldr max x xs
写法简洁,适合处理大型或惰性列表,可提前终止不必要的计算。
内容的提问来源于stack exchange,提问作者Brendan Langfield
相关产品推荐
相关产品推荐

