Reputation: 3562
I'm trying to implement a generic compose combinator
Recall that the composition of two functions—f and g-- is h(x) = f(g(x))
def inc(x: Double) = x + 1
def double(x: Double) = 2 * x
def compose[T](f: T, g: T, x: Int) = f(g(x))
println(compose(double, inc, 2))
I'm getting errors no matter what I try to do, I think I have a misunderstanding on generics or passing in functions...
What I want the compose function to do is take in two functions and execute f(g(x)) which would do g(x) first, then f(result of g(x)). In my example the result should be: 2(2+1) = 6
Question: How can I refactor my code to do this?
Upvotes: 2
Views: 255
Reputation: 3863
if you want to compose the functions, you have to make sure that the types match.
def compose[A,B,C](f: B => C, g: A => B, x: A): C = f(g(x))
println(compose(double, inc, 2.toDouble))
Then you can compose them. These combinators are already provided in Scala so you could do:
val inc = (v: Double) => v +1
val double = (v: Double) => v * 2
inc.andThen(double)
Upvotes: 3