Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala, Composing Function with two values

Tags:

scala

def adder(a:Int,b:Int):Int = {a+b}
def doubler(a:Int):Int = {a*2}
def doubleAdd = doubler _ compose adder

I get the error: type mismatch found: (Int,Int)=>Int required: ? => Int

Then if I just try doubleAdd = doubler(adder _) I get the same error except required Int instead of ? => Int

Is there a way of composing a function with two parameters? Sorry if this is pretty basic, I'm pretty new to the language, and I couldn't find an example with two parameters anywhere.

like image 877
Jim Avatar asked Nov 24 '14 17:11

Jim


People also ask

Is it possible to compose any two functions?

If we are given two functions, it is possible to create or generate a “new” function by composing one into the other. The step involved is similar when a function is being evaluated for a given value.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What is function composition in Scala?

Function composition is a way in which a function is mixed with other functions. During the composition the one function holds the reference to another function in order to fulfill it's mission.


1 Answers

You're attempting to compose a Function2 (adder) with a Function1, hence the issue. One workaround is to change your definition of Adder to a curried version:

def adder(a: Int)(b: Int):Int = a + b

Then doubleAdd to partially apply adder like this:

def doubleAdd(x: Int) = doubler _ compose adder(x)

What's happening under the hood is transforming adder from a Function2 (Int, Int) => Int, to a Function1 (Int) => (Int) => Int, or a function that returns a function. You're then able to compose the function returned from adder with the first parameter already applied.

like image 114
Chris Avatar answered Sep 20 '22 17:09

Chris