Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell writing my own function to compose functions

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
like image 275
Bob Marley Avatar asked Jan 16 '26 23:01

Bob Marley


1 Answers

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".

like image 124
Cactus Avatar answered Jan 19 '26 19:01

Cactus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!