Library function to compose a function with itself n times

前端 未结 10 2004
野的像风
野的像风 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:25

    I'm a beginner in Haskell, currently on chapter 5 ("Higher Order Functions") of Learn You a Haskell For Great Good! so I'm not yet familiar with the functions shown in the previous replies. Given what I understand so far, I'd do it like this:

    applyNTimes :: Int -> (a -> a) -> a -> a
    applyNTimes n f x 
        | n == 0        = x
        | otherwise     = f (applyNTimes (n-1) f x)
    
    0 讨论(0)
  • 2020-11-30 04:27

    Another solution using foldr:

    \n -> flip (foldr ($)) . replicate n

    0 讨论(0)
  • 2020-11-30 04:29
    \xs n -> iterate func xs !! n
    

    (xs is the initial value, n is the number of times to apply func)

    I don't know why, but I feel like iterate is something people aren't consistently exposed to when learning Haskell.

    If you don't like !! then you could use zip and lookup as an alternative. (some people/groups/tools don't like functions that call "error" in certain cases, I'm not claiming lookup is any better in these cases)

    lookup n . zip [0..] . iterate func
    

    EDIT: Ok, so I deleted then undeleted because I agree with the other answerer - you shouldn't discount use of iterate just because it gives you more than you need.

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

    A variation on trinithis' answer using the newtype package, just for fun:

    (\n f -> under Endo (mconcat . replicate n) f)
    

    Or point-free:

    under Endo . (mconcat .) . replicate
    
    0 讨论(0)
提交回复
热议问题