使用高阶函数在 Haskell 中查找 Maybe 值列表的最大值
Finding max of a list of Maybe values in Haskell using Higher Order Functions
我正在尝试使用更高级别的顺序函数来获取 Maybe 值的列表和 return 一个 int 类型的最大值,但由于某种原因我只能 return 一个 Maybe 值。
例如,这有效:
max' iL = foldl maxMaybe Nothing iL
maxMaybe Nothing y = Just y
maxMaybe (Just x) y = Just (max x y)
然而,这并不像它所说的那样,它仍然需要一个 Maybe 值,但它正在为结果生成一个 int:
max' iL = foldl maxMaybe (minBound::Int) iL
maxMaybe Nothing y = y
maxMaybe (Just x) y = (max x y)
对于第二种实现,您使用了错误的累加器类型,因为 foldl
的累加器是其函数的第一个参数 - 这里是 maxMaybe
函数-,我们必须交换参数maxMaybe
:
max' :: Foldable t => t (Maybe Int) -> Int
max' = foldl maxMaybe (minBound::Int)
maxMaybe :: Ord a => a -> Maybe a -> a
maxMaybe y Nothing = y
maxMaybe y (Just x) = max x y
此函数现在可用,但我认为此方法不是查找最大值的好方法,我更喜欢第一种实现,因为您可以对其结果进行模式匹配。
我建议将第一个实现更改为这个,因为 foldlr
更适合 haskell foldr 而 Just (Just a)
是多余且丑陋的:
maxWithFoldlr = (Foldable t, Ord a) => t (Maybe a) -> Maybe a
maxWithFoldlr = foldlr maxMaybe Nothing
maxWithFoldl :: (Foldable t, Ord a) => t (Maybe a) -> Maybe a
maxWithFoldl = foldl maxMaybe Nothing
maxMaybe :: Ord a => Maybe a -> Maybe a -> Maybe a
maxMaybe Nothing y = y
maxMaybe x Nothing = x
maxMaybe (Just x) (Just y) = Just $ max x y
我正在尝试使用更高级别的顺序函数来获取 Maybe 值的列表和 return 一个 int 类型的最大值,但由于某种原因我只能 return 一个 Maybe 值。 例如,这有效:
max' iL = foldl maxMaybe Nothing iL
maxMaybe Nothing y = Just y
maxMaybe (Just x) y = Just (max x y)
然而,这并不像它所说的那样,它仍然需要一个 Maybe 值,但它正在为结果生成一个 int:
max' iL = foldl maxMaybe (minBound::Int) iL
maxMaybe Nothing y = y
maxMaybe (Just x) y = (max x y)
对于第二种实现,您使用了错误的累加器类型,因为 foldl
的累加器是其函数的第一个参数 - 这里是 maxMaybe
函数-,我们必须交换参数maxMaybe
:
max' :: Foldable t => t (Maybe Int) -> Int
max' = foldl maxMaybe (minBound::Int)
maxMaybe :: Ord a => a -> Maybe a -> a
maxMaybe y Nothing = y
maxMaybe y (Just x) = max x y
此函数现在可用,但我认为此方法不是查找最大值的好方法,我更喜欢第一种实现,因为您可以对其结果进行模式匹配。
我建议将第一个实现更改为这个,因为 foldlr
更适合 haskell foldr 而 Just (Just a)
是多余且丑陋的:
maxWithFoldlr = (Foldable t, Ord a) => t (Maybe a) -> Maybe a
maxWithFoldlr = foldlr maxMaybe Nothing
maxWithFoldl :: (Foldable t, Ord a) => t (Maybe a) -> Maybe a
maxWithFoldl = foldl maxMaybe Nothing
maxMaybe :: Ord a => Maybe a -> Maybe a -> Maybe a
maxMaybe Nothing y = y
maxMaybe x Nothing = x
maxMaybe (Just x) (Just y) = Just $ max x y