全新的 Haskell 和通过 Learn Haskell 学习更大的好处。
我在看 map 功能
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
是否可以为此添加谓词?例如,只映射到列表中的所有其他元素?
最佳答案
您可以编写自己的版本 map
申请 f
仅对偶数(或奇数)位置如下。 (以下索引从 0
开始)
mapEven :: (a->a) -> [a] -> [a]
mapEven f [] = []
mapEven f (x:xs) = f x : mapOdd f xs
mapOdd :: (a->a) -> [a] -> [a]
mapOdd f [] = []
mapOdd f (x:xs) = x : mapEven f xs
如果你想利用库函数,你可以做类似的事情
mapEven :: (a->a) -> [a] -> [a]
mapEven f = map (\(flag,x) -> if flag then f x else x) . zip (cycle [True,False])
甚至
mapEven :: (a->a) -> [a] -> [a]
mapEven f = map (uncurry (\flag -> if flag then f else id)) . zip (cycle [True,False])
如果要使用索引上的任意谓词进行过滤,则:
mapPred :: (Int -> Bool) -> (a->a) -> [a] -> [a]
mapPred p f = map (\(i,x) -> if p i then f x else x) . zip [0..]
使用
zipWith
可以获得更直接的解决方案(正如@amalloy 所建议的那样)。mapEven :: (a->a) -> [a] -> [a]
mapEven f = zipWith (\flag x -> if flag then f x else x) (cycle [True,False])
这可以进一步细化如下
mapEven :: (a->a) -> [a] -> [a]
mapEven f = zipWith ($) (cycle [f,id])
关于haskell - 向 map 函数添加谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25403482/