Sunday 15 March 2015

haskell - Can mapEvery be implemented with foldr -



haskell - Can mapEvery be implemented with foldr -

for function maps function every nth element in list:

mapevery :: int -> (a -> a) -> [a] -> [a] mapevery n f = zipwith ($) (drop 1 . cycle . take n $ f : repeat id)

is possible implement foldr ordinary map?

edit: in title, changed 'folder' 'foldr'. autocorrect...

here's 1 solution

mapevery :: int -> (a -> a) -> [a] -> [a] mapevery n f = foldr go (const []) 1 go m | m == n = f : 1 | otherwise = : (m+1)

this uses "foldl foldr" trick pass state left right along list fold. essentially, if read type of foldr (a -> r -> r) -> r -> [a] -> r instantiate r int -> [a] passed integer current number of elements we've passed without calling function.

haskell functional-programming fold

No comments:

Post a Comment