Scala Curry Example

I am new to scala and have taken the coursera course for the functional development of scala. The code snippet below explains currying

import math.abs

object exercise{
    val tolerance = 0.0001

    def isCloseEnough(x: Double, y: Double) = abs((x -y)/x)/x < tolerance

    def fixedPoint(f: Double => Double)(firstGuess: Double) = {
      def iterate(guess: Double):Double = {
        val next = f(guess)
          if ( isCloseEnough(guess, next)) next
          else iterate(next)
        }
      iterate(firstGuess)
    }

    def averageDamp(f: Double => Double)(x: Double) = ( x + f(x))/2

    def sqrt(x: Double) = fixedPoint( averageDamp(y => x/y))(1)
}

I can not understand the next part of the code

fixedPoint( averageDamp(y => x/y))(1)

I know that the averageDamp function takes 2 arguments (one is the function and the other is the value for x), but when it is called from fixedPoint, we do not pass the value of x. Therefore, I assumed that it creates a partial function that is sent back to sqrt, where the value of x is passed from the sqrt (x: Double) agrument. So I made the following function, which does not compile

def noIdea(x: Double) = averageDamp( y => x/y)

Can someone explain this to me?

+4
source share
2 answers

, eta . , . Scala , , eta . .

, Scala, 2.11.7 . :

scala> def my_scaler(sc: Double)(x: Double): Double = sc*x

my_scaler: (sc: Double)(x: Double)Double

scala> def my_doubler = my_scaler(2d) // no eta exp
<console>:13: error: missing argument list for method my_scaler
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `my_scaler _` or `my_scaler(_)(_)` instead of `my_scaler`.
       def my_doubler = my_scaler(2d)
                                 ^

scala> def my_doubler = my_scaler(2d) _ // manual eta exp
my_doubler: Double => Double

scala> my_doubler(10d)
res1: Double = 20.0

scala> def my_tripler: Double => Double  = my_scaler(3d) // auto eta exp
my_tripler: Double => Double

scala> my_tripler(10d)
res2: Double = 30.0
+2

, , , - , . fixedPoint , :

fixedPoint( averageDamp(y => x/y))(1)

, Scala, _ (_)(_), :

def noIdea(x: Double) = averageDamp( y => x/y) _

noIdea:

def noIdea(x: Double): Double => Double  = averageDamp( y => x/y)

_ - , , .

+4

Source: https://habr.com/ru/post/1669217/


All Articles