Haskell 根据特定规则连接/过滤
Haskell concat / filter according specific rules
根据以下规则,我尝试解决了以下问题:
- 没有定义递归
- 无理解列表
- 只允许 Prelude-Module。
现在我必须为 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 函数正在运行(到目前为止没有什么特别的)-> 这是定义的递归吗?我的意思是我使用 standard-prelude 中的预定义 concat 但我自己没有定义它 - 或者我错了吗?
对于过滤器,函数我已经查找了标准序曲的定义,但它要么不起作用,要么包含递归的定义。
我假设应该避免使用 concat
和 filter
函数。如果 concat
和 filter
已经可用,为什么我们需要实施它们?所以尝试从头开始实现它们。
我们可以使用 folding 而不是递归和列表理解。以下解决方案使用函数 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]
您可以进行以下操作;
concat' :: Monad m => m (m b) -> m b
concat' = (id =<<)
filter' p = ((\x-> if p x then [x] else []) =<<)
=<<
只是单子绑定运算符 >>=
.
的翻转版本
filter' (< 10) [1,2,3,10,11,12]
[1,2,3]
根据以下规则,我尝试解决了以下问题:
- 没有定义递归
- 无理解列表
- 只允许 Prelude-Module。
现在我必须为 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 函数正在运行(到目前为止没有什么特别的)-> 这是定义的递归吗?我的意思是我使用 standard-prelude 中的预定义 concat 但我自己没有定义它 - 或者我错了吗?
对于过滤器,函数我已经查找了标准序曲的定义,但它要么不起作用,要么包含递归的定义。
我假设应该避免使用 concat
和 filter
函数。如果 concat
和 filter
已经可用,为什么我们需要实施它们?所以尝试从头开始实现它们。
我们可以使用 folding 而不是递归和列表理解。以下解决方案使用函数 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]
您可以进行以下操作;
concat' :: Monad m => m (m b) -> m b
concat' = (id =<<)
filter' p = ((\x-> if p x then [x] else []) =<<)
=<<
只是单子绑定运算符 >>=
.
filter' (< 10) [1,2,3,10,11,12]
[1,2,3]