Johnylikes3thirty
Johnylikes3thirty

Reputation: 1

Function composition in Haskell to calculate Power

i am trying to write a power function in haskell that calculates f to the power of n, where f is a function itself, using function composition.

This is what I have so far:

let pow 0 f = (\x -> x)
    pow n f = f . (pow (n-1) f) 
in 2 ((\x -> x+1) 2)

I am expecting it to pass the function f(x)=x+1 to power function and return the square of the function. I try passing in the value 2 to the f(x) function, so i thought it would return 4

When I run it on haskell.org I get:

:: (Num a, Num (a -> t)) => t

Upvotes: 0

Views: 376

Answers (1)

Amadan
Amadan

Reputation: 198314

Your line is invalid: 2 ((\x->x+1) 2) is malformed (as it is equivalent to 2 3).

let pow 0 f = (\x->x); pow n f = f.(pow (n-1) f) in (pow 2 (\x -> x + 1)) 2

does produce 4.

Upvotes: 2

Related Questions