Created
August 1, 2014 03:45
-
-
Save weefbellington/3a0aec102b02a483e74a to your computer and use it in GitHub Desktop.
higher-order functions (sliding window)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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