我想在整数列表中找到最大的整数值。以下是我的代码 -
maximum :: [Int] -> Int
maximum [x] = x
maximum (x:xs) =
| (maximum xs) > x = maximum xs
| otherwise = x
Run Code Online (Sandbox Code Playgroud)
我不想使用内置函数 max。所以,我没有使用过:maximum (x:xs) = max x (maximum xs)
为什么代码没有执行?
您应该删除=wards 块之前的 。现在,为了使您的功能正常:
你可以fold列出:
maximum' :: Ord a => [a] -> a
maximum' = foldr1 (\x y ->if x >= y then x else y)
Run Code Online (Sandbox Code Playgroud)
对于递归版本(没有双重检查):
maximum'' :: Ord a => [a] -> a
maximum'' [x] = x
maximum'' (x:x':xs) = maximum' ((if x >= x' then x else x'):xs)
Run Code Online (Sandbox Code Playgroud)
如果你想要病房:
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)
Run Code Online (Sandbox Code Playgroud)
这里有一个活生生的例子
=在第一个之前你还有一个额外的|。
maximum (x:xs) | (maximum xs) > x = maximum xs
| otherwise = x
Run Code Online (Sandbox Code Playgroud)
请注意,您计算了maximum xs两次,这可能会使您的代码运行速度非常慢。