首页 > 解决方案 > Scala 中函数类型的类型别名

问题描述

我是最新的 Scala 语言,但我不明白它是如何type Set = Int => Boolean工作的。我知道这是与布尔值转换的整数。我有def map(s: Set, f: Int => Int): Set = y => exists(s, x => y == f(x))For 存在def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, i => !p(i)))和

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)
  }

这两个功能我理解,但map功能有问题。我只是不明白,如果我打电话给它,它是如何显示答案map(Set(2,3,5), i => i * 20)的。我明白了{40,60,100}。我试图理解它,我知道其中x的每个元素都是 x 元素sf(x)它乘以 20。y范围从 -1000 到 1000 ( bound = 1000)。我读这个函数是这样的: yis range -1000..1000in exists function is getting our Set(2,3,5)and after it give somthing with Boolean type. 我是如何得到答案的{40,60,100}。新系列是如何在那里创建的?

完整代码->

  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)))

标签: scalafunctiontypesfunctional-programmingalias

解决方案


鉴于map()实施...

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

...和调用...

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

...做一些替换,你会得到:

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

作为 a Setis Int => Boolean(一个接受 anInt并返回truefalse的函数),mappedSet是一个要求:

给定一个数字 ,y在 +-bounds 中是否存在一个既通过(是其中的成员)Set(2,3,5)并且当乘以 20 时等于 的数字y

mappedSet(60)返回true因为在 +-bounds 内确实存在一个数字 ,3它既是Set(2,3,5)AND 的成员,当乘以 20 时,等于60

mappedSet(80)返回false,因为找不到通过这两个测试的数字。


推荐阅读