根据以下规则,我尝试解决以下问题:
现在,我必须为concat和filter实现高阶。
我在这一点上:
concat' :: [[a]] -> [a]
concat' a = (concat a)
filter' :: (a -> Bool) -> [a] -> [a]
filter' p [] = []
filter' p (x:xs)
| p x = x : filter p xs
| otherwise = filter p xs
concat函数正在运行(到目前为止没有什么特别的)->这是已定义的递归吗?我的意思是我使用的是标准前奏中的预定义concat,但我自己却没有定义它-还是我错了?
对于过滤器,我查找了标准前奏的定义的函数,但该函数不起作用,并且包含递归的定义。
我想应该避免使用concat
andfilter
函数。为什么需要实施concat
,filter
如果它们已经可用?因此,请尝试从头开始实施它们。
我们可以使用折叠来代替递归和列表推导。以下解决方案使用函数foldr
。
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
concat' :: [[a]] -> [a]
concat' = foldr (++) []
filter' :: (a -> Bool) -> [a] -> [a]
filter' p = foldr (\x acc -> if p x then x:acc else acc) []
例子:
main = do
print $ concat' ["A", "B", "CAB"] -- "ABCAB"
print $ filter' (\x -> x `mod` 2 == 0) [1..9] -- [2, 4, 6, 8]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句