[英]Haskell - Max number in a list
我想在整数列表中找到最大的整数值。 以下是我的代码 -
maximum :: [Int] -> Int
maximum [x] = x
maximum (x:xs) =
| (maximum xs) > x = maximum xs
| otherwise = x
我不想使用内置的 function 最大值。 所以,我没有使用:maximum (x:xs) = max x (maximum xs)
为什么代码不执行?
第一个|
之前有一个额外的=
|
。
maximum (x:xs) | (maximum xs) > x = maximum xs
| otherwise = x
请注意,您两次计算maximum 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)
这里有一个现场例子
首先存在语法错误,您需要在maximum (x:xs)
之后删除=
。
其次,函数maximum
与Main.maximum
冲突,建议您重命名它,例如:
maximum' :: [Int] -> Int
maximum' [x] = x
maximum' (x:xs)
| (maximum' xs) > x = maximum' xs
| otherwise = x
递归
使用where
子句
maxrec :: (Ord a) => [a] -> a
maxrec [] = error "maximum of empty list"
maxrec [x] = x
maxrec (x:xs)
| x > maxTail = x
| otherwise = maxTail
where maxTail = maxrec xs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.