我正在尝试编写函数,但我不知道为什么我不能那样做
ssm' = foldr (\x acc -> if acc == [] then [x]++acc else if (x > (maximum acc)) then [x]++acc else acc) []
请给我一个线索。
顺便说一句,您的代码看起来太复杂了。你用错了if
,[x]++acc
只是x:acc
。acc
每一步扫描maximum
都是浪费,因为它最大的元素必须是它的头部。总而言之,我会写:
ssm' :: Ord a => [a] -> [a]
ssm' = foldr go [] where
go x [] = [x]
go x ms@(m:_)
| x > m = x:ms
| otherwise = ms
如果你真的喜欢单线,试试
import Data.List
ssm' xs = reverse $ map head $ groupBy (>) (reverse xs)
您遇到了单态限制。您可以通过添加类型签名来修复它。
ssm' :: Ord a => [a] -> [a]
ssm' = ...