I recently noticed that I quite often write functions which just iterates another function f
until it reaches a fixed point (such that f x == x
)
I thought this is a pretty general concept, so I think there might be a built in.
So I was wondering whether there is a built in for this, or something more general?
So I'm basically looking for this:
fixedpoint f x= head . dropWhile(\y->y /= f y) $ iterate f x
I just had trouble googling this, because I only found references to the fix
function whenever my search term contained fixed point
or something similar.
fix will find a fixed point of fact' , i.e. the function f such that f == fact' f . But let's expand what this means: f = fact' f = \n -> if n == 0 then 1 else n * f (n-1) All we did was substitute rec for f in the definition of fact' . But this looks exactly like a recursive definition of a factorial function!
The sequence (n:ns) is a shorthand for head - tail. Quite literally, the first value, the head, is called n and the remained are the other, potentially plural, n s, which is why it is called ns . Haskell has pattern matching.
The Either type is sometimes used to represent a value which is either correct or an error; by convention, the Left constructor is used to hold an error value and the Right constructor is used to hold a correct value (mnemonic: "right" also means "correct").
Just write it yourself. A direct version will be faster than one using dropWhile
.
hammer :: Eq a => (a -> a) -> a -> a
hammer f x
| x' == x = x'
| otherwise = hammer f x'
where x' = f x
Your function has the signature Eq a => (a -> a) -> a -> a
.
Using hoogle to search for that, I don't see any exact matches. The closest match is until
until :: (a -> Bool) -> (a -> a) -> a -> a
base Prelude
until p f
yields the result of applyingf
untilp
holds.
You could likely use that to write your function but because you need /=
you need the Eq
constraint.
In case you are looking for a build-in because you want a short expression without any auxiliary functions, I can recommend
until=<<((==)=<<) :: Eq a => (a -> a) -> a -> a
Arguably this looks a bit strange, but in fact it is just the point-free equivalent to until (\x -> f x == x) f
, using the fact that f (g x) x
can be expressed by (f=<<g) x
twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With