KoreanFoodie's Study

Scala 4 - Closures, revisted 본문

Tutorials/Scala

Scala 4 - Closures, revisted

GoldGiver 2019. 4. 23. 18:59

 

스칼라 튜토리얼, scala의 closure에 대해 알아보자


Parameterized expression vs. values

Functions defined using “def” are not values but parameterized
expressions.

• Anonymous functions are values.

• But, parameterized expressions are implicitly converted to values.

• Explicit conversion: f _

• Anonymous functions can be seen as syntactic sugar:


(x:T)=>e

is equivalent to


{ def \_\_noname(x:T) = e; \_\_noname \_ }

as long as __noname is not used in e.

One can even write a recursive anonymous function in this way.

• Q: what’s the difference between param. exps and function values?

A: functions values are “closures” (ie, param. exp. + env.)

• Q: how to implement call-by-name?

A: The argument expression is converted to a closure.

 

  • Example :

val t = 0  
def f(x: => Int) = t + x // x is treated as x()  
val r = {  
val t = 10  
f(t_t) // t_t is treated as () => t\*t  
}

 

  • Clousure, revisited

Let's look at the sample code.


val t = 0  
val f = {  
val t = 10  
def g(x: Int) : Int = x + t  
g \_  
}  
f(20)

We can change this follwing code, to clarify how closure works.


val t = 5  
def f: Double => Double = {  
val t = 10  
def g(x: Double): Double = x + t  
// if we use 'def g(x:Int): Double' -> ERROR!!  
g \_  
}  
f(20)

We changed 'f' by using 'def' instead of 'val', and we have to change parameter type and return type of 'g' as well. Otherwise, it causes error!


Forward reference

Let's look at this code.


{  
val t = 10  
def g(x:Int): Int = x + y + t  
val a = g(0)  
def y = 20 + t  
g(20)  
}

It produces error, in 'y'. (Error message: Wrong Forward Reference)

So, forward reference indicates 2 things. You can use variables not computed(if it is declared by 'def'), but statement using 'val' should not be placed between 'def' statements, when 'def' statement after that is used in 'val' statement's computation.

So, if you move val a = g(0) to the next line of def y = 20 + t,

```

{
val t = 10
def g(x:Int): Int = x + y + t
def y = 20 + t
val a = g(0)
g(20)
}

~

No error, we get 60 for g(20). This kind of error checking machanism is called "Type Checker".

'Tutorials > Scala' 카테고리의 다른 글

Scala 6 - Datatypes  (0) 2019.04.23
Scala 5 - Currying  (0) 2019.04.23
Scala 3 - Tail Recursion & Higher-Order Functions 1  (0) 2019.04.23
Scala 2 - Blocks in Scala & Lazy val  (0) 2019.04.23
Scala 1 - Call by value vs. Call by name  (0) 2019.04.23
Comments