I always did something like iterate f x !! n
.
Apply a function multiple times in Haskell [duplicate]
-
20-06-2023 - |
Pergunta
Learn You a Haskell For Great Good (section "Higher Order Functions", subsection "Some higher-orderism is in order") describes an example function applyTwice
that calls a function on an argument twice:
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
But i need a function that applies some function over some argument an arbitrary amount of times. For example applyN 3 f x
would be equivalent to f $ f $ f x
. How would i write a function of repeated application in Haskell? Please post any possible solutions, using recursion, higher-order functions or anything else.
Solução
Outras dicas
You will have to do a recursive function. The obvious case will be be when you apply the function 0 time, it will be like you don't modify the input. The recursive will come from the fact that applyN n f x == f (applyN (n -1) f x
or because composition of function is associative applyN n f x == apply (n - 1) f (f x)
. The second option lead to better performance because it will be tail recursive
applyN :: Int n => n -> (a -> a) -> a -> a
applyN 0 _ x = x
applyN n f x = applyN (n - 1) f (f x)
applyN = (foldr (.) id.) . replicate
-->>
applyN 0 f = id
applyN 1 f = f
applyN 2 f = (f.f)
-- ...
Or just use iterate, as was already said before. The only real difference is that using iterate you will get an exception if you use a negative n, whereas in this solution you'd get id
. If that's a case that can plausibly happen for your use case, you should consider which is the behavior you like better.