Skip to content

Instantly share code, notes, and snippets.

@luqui
Last active December 27, 2019 04:00
Show Gist options
  • Save luqui/ed51bd523e025a5f4b98feaffcdec8f6 to your computer and use it in GitHub Desktop.
Save luqui/ed51bd523e025a5f4b98feaffcdec8f6 to your computer and use it in GitHub Desktop.
Example of how to get intermediate results from a Fold
import qualified Control.Foldl as Foldl
average :: Foldl.Fold Double Double
average = (/) <$> Foldl.sum <*> Foldl.genericLength
-- This could have been done more easily with the Foldl.scan function, but
-- I wanted to demonstrate how to access the intermediate states manually.
averages :: [Double] -> [Double]
averages xs
| Foldl.Fold step s0 obs <- average
= obs <$> scanl step s0 xs
main = print $ averages [1,2,3,4,5]
-- [NaN,1.0,1.5,2.0,2.5,3.0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment