blue-sky
blue-sky

Reputation: 53826

Function evaluation

In this question Invoking function which accept functions as parameters is this also a valid explanation of why the code does not compile?

funParam(3) is a valid invocation but fun(funParam(3)) is not. funParam(3) is not evaluated until compilation so the compiler cannot accept this as a valid parameter.

I think I'm confused as it's common practice to pass parameters to functions pre compilation but it is not valid to pass functions which contain parameters to functions pre compilation?

Upvotes: 0

Views: 100

Answers (3)

acjay
acjay

Reputation: 36551

I think you may be confusing a couple concepts.

It's worth thinking about why a function might take another function as a parameter. Given fun: (Int => Int) => Int (a function that takes a function of Int => Int as a parameter and returns an Int), presumably, fun is planning to pass an Int to its argument, and return some modified version of the result. This pattern is used frequently in functional programming, like when we pass functions to map or reduce that operate on values inside a collection. The argument of type Int => Int to fun is essentially a calculation with a "hole" in it, and it's counting on fun or some other operation to provide the Int it needs to be fully evaluated.

funParam(3) doesn't have any unspecified variables, and it will be evaluated immediately whenever it's referred to. That's why the type of funParam(3) is Int. Sure, funParam itself is Int => Int, but since you've given it the Int parameter 3, the type of the whole expression is just the return type: Int.

Upvotes: 1

Rado Buransky
Rado Buransky

Reputation: 3294

The reason is because fun expects Int => Int as an argument, but funParam(3) is not of that type. Its type is Int.

Upvotes: 1

Michael Zajac
Michael Zajac

Reputation: 55569

Given

def funParam(i: Int): Int = ...

You can treat the methodfunParam as a function with type Int => Int

But funParam(3) is not a function, it is a concrete value--an Int, and therefore not Int => Int

So you cannot pass an Int to a method that is expecting Int => Int.

Upvotes: 1

Related Questions