Skip to content

Instantly share code, notes, and snippets.

@weefbellington
Created August 1, 2014 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weefbellington/3a0aec102b02a483e74a to your computer and use it in GitHub Desktop.
Save weefbellington/3a0aec102b02a483e74a to your computer and use it in GitHub Desktop.
higher-order functions (sliding window)
windowMap :: ( a -> a -> b) -> [a] -> [b]
windowMap func list =
let zipped = zip list (tail list)
in map (uncurry func) zipped
windowScan :: (b -> a -> a -> b) -> b -> [a] -> [b]
windowScan func accumulator list =
let zipped = zip list (tail list)
func' = \ acc -> uncurry (func acc)
in scanl func' accumulator zipped
windowFold :: (b -> a -> a -> b) -> b -> [a] -> b
windowFold func accumulator list =
let zipped = zip list (tail list)
func' = \ acc -> uncurry (func acc)
in foldl func' accumulator zipped
list = [1..8]
testWindowMap :: [Integer] -> [Integer]
testWindowMap aList =
windowMap (+) aList
testWindowScan :: [Integer] -> [Integer]
testWindowScan aList =
windowScan scanFunc 1000 aList
scanFunc :: Integer -> Integer -> Integer -> Integer
scanFunc accumulator a b = accumulator - (a * b)
-- attempt to generalize the windowing behavior over multiple higher-order functions
window :: (((a, a) -> b) -> [(a, a)] -> r) -> (a -> a -> b) -> [a] -> r
window higherOrderFunc mergeApplicator list =
let zipped = zip list (tail list)
in higherOrderFunc (uncurry mergeApplicator) zipped
-- it works for map
windowMap' = window map
-- it doesn't work for scan, different function signature
-- windowScan' = window scanl
testWindowMap' :: [Integer] -> [Integer]
testWindowMap' aList =
windowMap' (+) aList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment