使用索引列表实现 map 函数
Implementing the map function with a list of indices
我只想为特定索引实现映射功能,如下所示:
mapFor :: (a -> a) -> [Int] -> [a] -> [a]
示例如下所示。
mapFor (+10) [0,2] [1,2,3,4] == [11,2,13,4]
使用数据来寻找模式,以满足给定的要求:
mapFor (+1) [0,2] [100,200,300,400] == [101,200,301,400] ==
= { [ 100, 200, 300, 400 ] -- values
[ 0, 1, 2, 3 ] -- indices
[ 0, 2 ] } -- places
--------------------------------------
= (100+1) : { [200, 300, 400 ] -- values
[ 1, 2, 3 ] -- indices
[ 2 ] } -- places
--------------------------------------
= (100+1) : 200 : { [300, 400 ] -- values
[ 2, 3 ] -- indices
[ 2 ] } -- places
--------------------------------------
= (100+1) : 200 : (300+1) : { [400 ] -- values
[ 3 ] -- indices
[] } -- places
--------------------------------------
=
........
其中 { ... }
表示我们的转换。
然后,泛化! -- 通过用符号变量替换具体数据,你就得到了一个有效的 -- 递归 -- 代码。
mapFor op places values = g [0..] places values
where
g (i:is) (p:ps) (v:vs) -- most general case
| i == p = ....
| otherwise = ....
g _ [] _ = .... -- base case
...... -- more corner cases, if any
确保你用尽所有可能性你的模式。
感谢@cornuz 我弄明白了。
mapFor f is xs = [if (i `elem` is) then f v else v | (i,v) <- zip [0..] xs]
如果您发现任何问题,请告诉我,以便我解决。
我只想为特定索引实现映射功能,如下所示:
mapFor :: (a -> a) -> [Int] -> [a] -> [a]
示例如下所示。
mapFor (+10) [0,2] [1,2,3,4] == [11,2,13,4]
使用数据来寻找模式,以满足给定的要求:
mapFor (+1) [0,2] [100,200,300,400] == [101,200,301,400] ==
= { [ 100, 200, 300, 400 ] -- values
[ 0, 1, 2, 3 ] -- indices
[ 0, 2 ] } -- places
--------------------------------------
= (100+1) : { [200, 300, 400 ] -- values
[ 1, 2, 3 ] -- indices
[ 2 ] } -- places
--------------------------------------
= (100+1) : 200 : { [300, 400 ] -- values
[ 2, 3 ] -- indices
[ 2 ] } -- places
--------------------------------------
= (100+1) : 200 : (300+1) : { [400 ] -- values
[ 3 ] -- indices
[] } -- places
--------------------------------------
=
........
其中 { ... }
表示我们的转换。
然后,泛化! -- 通过用符号变量替换具体数据,你就得到了一个有效的 -- 递归 -- 代码。
mapFor op places values = g [0..] places values
where
g (i:is) (p:ps) (v:vs) -- most general case
| i == p = ....
| otherwise = ....
g _ [] _ = .... -- base case
...... -- more corner cases, if any
确保你用尽所有可能性你的模式。
感谢@cornuz 我弄明白了。
mapFor f is xs = [if (i `elem` is) then f v else v | (i,v) <- zip [0..] xs]
如果您发现任何问题,请告诉我,以便我解决。