我想在整数列表中找到最大整数值。以下是我的代码 -
maximum :: [Int] -> Int
maximum [x] = x
maximum (x:xs) =
| (maximum xs) > x = maximum xs
| otherwise = x
我不想使用内置函数 max。所以,我没有使用过:
最大值 (x:xs) = 最大值 x (最大值 xs)
为什么代码没有执行?
最佳答案
您应该删除 =
在病房街区之前。
现在,为了使您的功能正确:
您可以fold
名单:
maximum' :: Ord a => [a] -> a
maximum' = foldr1 (\x y ->if x >= y then x else y)
对于递归版本(无双重检查):
maximum'' :: Ord a => [a] -> a
maximum'' [x] = x
maximum'' (x:x':xs) = maximum' ((if x >= x' then x else x'):xs)
如果你想要病房:
maximum'' :: Ord a => [a] -> a
maximum'' [x] = x
maximum'' (x:x':xs) | x >= x' = maximum' (x:xs)
maximum'' (x:x':xs) | otherwise = maximum' (x':xs)
在这里你有一个live example
关于Haskell - 列表中的最大数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45917027/