Home > Enterprise >  Type Alias for Function Types in Scala [closed]
Type Alias for Function Types in Scala [closed]

Time:09-17

I'm newest in Scala language and I can't understand how type Set = Int => Boolean works. I understand that it's something integer conversing to Boolean. I have def map(s: Set, f: Int => Int): Set = y => exists(s, x => y == f(x)) For exist def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, i => !p(i))) and

def forall(s: Set, p: Int => Boolean): Boolean = {
    def iter(a: Int): Boolean = {
      if (a > bound) true
      else if (diff(s,p)(a)) false
      else iter(a   1)
    }
    iter(-bound)
  }

This two functions I understand but with map function I have a problem. I just don't understand how does it show answer if I call it map(Set(2,3,5), i => i * 20) . I get {40,60,100}. I have tried to understand it and I know that x is each element in s and f(x) is x elemet which multiply in 20. And y is range from -1000 to 1000 (bound = 1000). My reading this function like this: y is range -1000..1000 in exists function is getting our Set(2,3,5) and after it give somthing with Boolean type. And how am I getting answer like {40,60,100}. How is new set creating there?

Full code ->

  type Set = Int => Boolean

  def contains(s: Set, elem: Int): Boolean = s(elem)
  def diff(s: Set, t: Set): Set = (i: Int)  => s(i) && !t(i)

  val bound = 1000

  def forall(s: Set, p: Int => Boolean): Boolean = {
    def iter(a: Int): Boolean = {
      if (a > bound) true
      else if (diff(s,p)(a)) false
      else iter(a   1)
    }
    iter(-bound)
  }

  def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, x => !p(x))
  def map(s: Set, f: Int => Int): Set = y => exists(s, x => y == f(x))

  def toString(s: Set): String = {
    val xs = for (i <- -bound to bound if contains(s, i)) yield i
    xs.mkString("{", ",", "}")
  }

  println(toString(map(Set(2, 3, 5), (i: Int) => i * 20)))

CodePudding user response:

Given the map() implementation...

y => exists(s, x => y == f(x))

...and the invocation...

map(Set(2,3,5), (i: Int) => i * 20)

...make a few substitutions, and you get:

val mappedSet = y => exists(Set(2,3,5), x => y == x*20)

As a Set is Int => Boolean (a function that takes an Int and returns true or false), mappedSet is a function that asks:

Given a number, y, does there exist a number within -bounds that both passes (is a member of) Set(2,3,5) and, when multiplied by 20, equals y?

mappedSet(60) returns true because within -bounds there does exist a number, 3, that is both a member of Set(2,3,5) AND, when multiplied by 20, equals 60.

mappedSet(80) returns false because no number can be found that passes both tests.

  • Related