Library function to compose a function with itself n times

前端 未结 10 2003
野的像风
野的像风 2020-11-30 03:36

Is there a library function available in Haskell to compose a function with itself n times?

For example I have this function:

func :: a ->         


        
相关标签:
10条回答
  • 2020-11-30 04:11

    The iterate solution is fine, or you might like this one: the composition of n copies of f is foldr (.) id (replicate n f).

    0 讨论(0)
  • 2020-11-30 04:12

    Here's a version that has complexity O(log n) instead of O(n) (to build the function, not to apply it):

    composeN 0 f = id
    composeN n f
        | even n = g
        | odd  n = f . g
        where g = g' . g'
              g' = composeN (n `div` 2) f
    
    0 讨论(0)
  • 2020-11-30 04:16

    I do not know why you say that iterate is not appropriate. It is perfectly suitable for this purpose. (!! n) . iterate func is the composition of n copies of func.

    (Someone had posted an answer similar to the above code, but he/she seems to have deleted it.)

    0 讨论(0)
  • 2020-11-30 04:19

    (\n -> appEndo . mconcat . replicate n . Endo) n f x

    0 讨论(0)
  • 2020-11-30 04:19
    \n -> appEndo . foldMap Endo . replicate n
    
    0 讨论(0)
  • 2020-11-30 04:19
    iterate (f .) id !! n
    

    or

    iterate (f .) f !! (n-1)
    

    depending on if n == 0 is allowed.

    0 讨论(0)
提交回复
热议问题