Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

andThen for function of two arguments in Scala

Tags:

function

scala

Suppose I have two functions f and g:

val f: (Int, Int) => Int = _ + _
val g: Int => String = _ +  ""

Now I would like to compose them with andThen to get a function h

val h: (Int, Int) => String = f andThen g

Unfortunately it doesn't compile :(

scala> val h = (f andThen g)
<console> error: value andThen is not a member of (Int, Int) => Int
   val h = (f andThen g)

Why doesn't it compile and how can I compose f and g to get (Int, Int) => String ?

like image 441
Michael Avatar asked Feb 17 '15 16:02

Michael


People also ask

How do you use andThen in Scala?

Val functions inherit the andThen function and we will show how to use the andThen function to compose two functions together. Mathematically speaking, (f andThen g)(x) = g(f(x)). The results of the first function f(x) is ran first and will be passed as input to the second function g(x).

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 .

How do you pass parameters to a Scala function?

Scala - Functions with Named Arguments Named arguments allow you to pass arguments to a function in a different order. The syntax is simply that each argument is preceded by a parameter name and an equals sign. Try the following program, it is a simple example to show the functions with named arguments.

What is function currying in Scala?

Currying is the process of converting a function with multiple arguments into a sequence of functions that take one argument. Each function returns another function that consumes the following argument.


2 Answers

It doesn't compile because andThen is a method of Function1 (a function of one parameter: see the scaladoc).

Your function f has two parameters, so would be an instance of Function2 (see the scaladoc).

To get it to compile, you need to transform f into a function of one parameter, by tupling:

scala> val h = f.tupled andThen g
h: (Int, Int) => String = <function1>

test:

scala> val t = (1,1)
scala> h(t)
res1: String = 2

You can also write the call to h more simply because of auto-tupling, without explicitly creating a tuple (although auto-tupling is a little controversial due to its potential for confusion and loss of type-safety):

scala> h(1,1)
res1: String = 2
like image 155
DNA Avatar answered Oct 28 '22 03:10

DNA


Function2 does not have an andThen method.

You can manually compose them, though:

val h: (Int, Int) => String = { (x, y) => g(f(x,y)) }
like image 22
Michael Zajac Avatar answered Oct 28 '22 04:10

Michael Zajac