Partial Applied Function in Recursion

I am new to Haskell. I wrote a function that applies a different function to an argument multiple times:

frepeat :: (Integral n) => n -> (a -> a) -> a -> a
frepeat n f a
    | n <= 0 = error "Invalid count."
    | n == 1 = f a
    | otherwise = f (frepeat (n-1) f a)

      

Works:

ghci> frepeat 3 (^2) 2
256
ghci> frepeat 4 (++ "-bla") "bla"
"bla-bla-bla-bla-bla"

      

Now I want to rewrite it more compactly, without the last argument. I want it to be a partial application function. I've tried this:

frepeat :: (Integral n) => n -> (a -> a) -> a -> a
frepeat n f
    | n <= 0 = error "Invalid count."
    | n == 1 = f
    | otherwise = f (frepeat (n-1) f)

      

But GHCi didn't eat it ... Does that mean I can't do it?

+3


source to share


1 answer


You only need one extra (.) In the last part

| otherwise = f . (frepeat (n-1) f)

      

In general, this



let f x = f (g x)

      

can be rewritten as

let f = f . g

      

+4


source







All Articles