3

so I am trying to write my own function to compose a function n times in Haskell.

so for example, the input

compose (+1) 3 

would return f(x) = x+3;

Now my attempt is as follows, but is actually quite naive and currently doesn't work.

compose f 0 = (*1)
compose f n = (compose f n-1).a

1 Answer 1

7

In the second case, you are trying to refer to a which I think you meant as f, since then

compose f n = (compose f (n-1)) . f

(note also that compose f n - 1 is parsed as (compose f n) - 1 in your code)

which means you have

compose f 3 = (compose (+1) 2)             . f
            = ((compose (+1) 1)       . f) . f
            = (((compose (+1) 0) . f) . f) . f
            = ((((*1)            . f) . f) . f

Oh and by the way, you can write

compose f 0 = id

which expresses the idea that compose f 0 should do "nothing".

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, so I was testing, and it seems the main issue I was having was brackets around 'n-1'. Do you perhaps have a reason why that screws up the function?
Yes, because then it gets parsed as ((compose f n) - 1) i.e. it's trying to subtract 1 from compose f n which is not a number.
Ok, thank you very much. That actually clarified a bunch.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.