gpt4 book ai didi

haskell - 如何通过可能的输出查找列表中的最大元素

转载 作者:行者123 更新时间:2023-12-02 13:39:43 24 4
gpt4 key购买 nike

此代码有效

max_elem :: (Ord a) => [a] -> a 
max_elem [x] = x
max_elem [] = error "No elements"
max_elem (x:xs)
|x > max_elem xs = x
|otherwise = max_elem xs

我想要它,所以如果它们没有元素并且只返回 x 作为最大元素,那么它会返回 Nothing我尝试了以下方法

max_elem :: (Ord a) => [a] -> Maybe a 
max_elem [x] = Just x
max_elem [] = Nothing
max_elem (x:xs)
|x > max_elem xs = Just x
|otherwise = max_elem xs

我收到以下错误。请提出解决此问题的建议。

 • Couldn't match expected type ‘a’ with actual type ‘Maybe a’
‘a’ is a rigid type variable bound by
the type signature for:
max_elem :: forall a. Ord a => [a] -> Maybe a
at <interactive>:208:13
• In the second argument of ‘(>)’, namely ‘max_elem xs’
In the expression: x > max_elem xs
In a stmt of a pattern guard for
an equation for ‘max_elem’:
x > max_elem xs
• Relevant bindings include
xs :: [a] (bound at <interactive>:211:13)
x :: a (bound at <interactive>:211:11)
max_elem :: [a] -> Maybe a (bound at <interactive>:209:1)

最佳答案

由于以下行,您会收到错误:x > max_elem xsmax_elem xs 的类型为 Maybe a,其中 a 是列表的元素。它的类型为a。您无法比较不同类型的值。 aMaybe a 是不同的类型。请参阅 Haskell 等式表:

== 运算符替换为 >,您将得到相同的表。

您可以通过将 x > max_elem xs 替换为 Just x > max_elem xs 来解决代码中的问题。这对你来说有意义吗?

如您所见,Maybe a 数据类型具有 Ord a => Ord (Maybe a) 实例,这实际上非常方便!因此,您可以使用此 Ord 实例以更简洁的方式实现您的函数:

max_elem :: Ord a => [a] -> Maybe a 
max_elem = foldr max Nothing . map Just

不过,如果您关心性能,这可能不是最有效的解决方案。

关于haskell - 如何通过可能的输出查找列表中的最大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49399176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com