Max Dude2014
Max Dude2014

Reputation: 21

Function Recursion within itself - haskell

I was trying to recursively pass a function to itself a given number of times. So given the input in form of Function | RepeatNumber(Count) | Argument. So as an example if given the input: f 3 2 it would return f(f(f 2) This should then also work if the Function value where "square" it would Square the argument.

In terms of the logic I approached it as follows:

def repeatnew func count arg
    if count == 1 then (func arg)
    else (func (repeatnew func (count -1) arg))

I've been trying to research a solution to this for a while and I came across using Iterate and some other functions. Finally I came across this: https://wiki.haskell.org/Higher_order_function However I was unable to implement a working solution.

Edit: The solutions I did try to implement I could get compiling correctly, I am still very inexperienced with haskell and would appreciate an explanation on how to create a higher order function using my parameters.

Upvotes: 2

Views: 784

Answers (2)

Redu
Redu

Reputation: 26161

Spinning off from @Antisthenes' comment, One other way to do this is using the foldl1 with no base case.

pipeNTimes :: (a -> a) -> Int -> (a -> a)
pipeNTimes f n = foldl1 (.) $ replicate n f

pipeNTimes (*2) 3 2 -- returns 16

Upvotes: 4

Matt Hogan-Jones
Matt Hogan-Jones

Reputation: 3103

I am admittedly only a beginner at Haskell, so this may be a naive implementation, but I think this does what you are looking for:

applyRecursively f x y
    | x == 1 = f y
    | otherwise = f (applyRecursively f (x-1) y)

The applyRecursively function takes a function and two numbers as arguments.

If the middle argument (the count) is 1 then we apply the parameter function to the argument y. This is the edge case that stops the recursion.

The otherwise guard clause then calls recursively with the x parameter decremented, and applies function f to the result.

I have tested it using a lambda like this:

applyRecursively (\x -> x + 1) 3 3

It should add 1 to the values of 3 three times - it returns a value of 6 so it looks like it works.

As I say, I'm a beginner but I think this does what you're looking for.

Upvotes: 2

Related Questions