Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala function => as parameter

Tags:

scala

Could anybody kindly explain to me why the following

  /**
   * Returns a set transformed by applying `f` to each element of `s`.
   */
    def map(s: Set, f: Int => Int): Set = x => exists(s, y => f(y) == x)

is not equivalent to

    def map(s: Set, f: Int => Int): Set = x => exists(s, f(x))

where "exists" is a function that returns whether there exists a bounded integer within s(the first argument) that satisfies p(the second argument).

Why do you need to specify "y => f(y) == x"? Thanks a million!

like image 259
iammyr Avatar asked Jun 29 '16 09:06

iammyr


1 Answers

exists's second argument has the type Int => Boolean (right?), in other words, it expects a function from Int to Boolean. Now, f(x) doesn't conform to that type - it has the type Int. So - y => f(y) == x creates a function with the correct type, that returns true if its input equals x.

If the excess characters bug you - you can also shorten it a bit using the anonymous argument '_':

def map(s: Set, f: Int => Int): Set = x => exists(s, f(_) == x)
like image 62
Tzach Zohar Avatar answered Oct 04 '22 13:10

Tzach Zohar