Right Arrow meanings in Scala -


in chapter 9 of programming in scala, there example method this:

def twice(op: double => double, x: double) = op(op(x)) 

the author said in book:

the type of op in example double => double, means function takes 1 double argument , returns double.

i don't understand "double => doulbe" here, in previous chapters, "=>" appears means function literal, , never wrote "type => type", because according scala function literal syntax defination, right part of function literal function body, how can function body "double" ?

because has 2 usages.

first, use => define function literal.

scala> val fun = (x: double) => x * 2 fun: (double) => double = <function1>  scala> fun (2.5) res0: double = 5.0 

it's pretty easy. question here is, type fun is? "function takes double argument , return double", right?

so how annotate fun type? (double) => (double). well, previous example rewritten to:

scala> val fun: double => double = (x: double) => x * 2 fun: (double) => double = <function1>  scala> fun (2.5)                                        res1: double = 5.0 

ok, following code do?

def twice(op: double => double, x: double) = op(op(x)) 

well, tells op (double => double), means needs function takes double , return double.

so pass previous fun function first argument.

scala> def twice(op: double => double, x: double) = op(op(x))     twice: (op: (double) => double,x: double)double  scala> twice (fun, 10) res2: double = 40.0 

and equivalent replacing op fun, , replace x 10, fun(fun(10)) , result 40.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -