Skip to content

Instantly share code, notes, and snippets.

@oakwhiz
Last active August 29, 2015 14:06
Show Gist options
  • Save oakwhiz/66854cbff68f64d1edc6 to your computer and use it in GitHub Desktop.
Save oakwhiz/66854cbff68f64d1edc6 to your computer and use it in GitHub Desktop.
Simulation combinator - iterates from a starting point toward a fixed point.
-- Simulation combinator.
-- If (f x /= x) then try f f x, f f f x, etc.
-- Keeps chaining f until nothing new happens, i.e. the simulation has "settled"
-- Similar to the fixed point combinator but with a starting condition.
simC :: Eq a => (a -> a) -> a -> a
simC f x | f x == x = x | otherwise = simC f (f x)
-- Same as above, but keeps a list of the intermediate states.
-- let simCList :: Eq a => (a->a) -> [a] -> [a]; simCList f x | f (last x) == (last x) = x | otherwise = simCList f (x ++ [f (last x)])
simCList :: Eq a => (a -> a) -> [a] -> [a]
simCList f x | f (last x) == (last x) = x | otherwise = simCList f (x ++ [f (last x)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment