Phillip R Phillip R - 3 years ago 152
Scala Question

Scala Functional Programming Generics

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?

Answer Source

if you want to compose to functions you have to make sure that the types matches

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. This combinators are already provided in Scala so you could do

val inc = (v: Double) => v +1
val double = (v: Double) => v * 2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download