本文介绍了斯卡拉的两套联盟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从链接的问题中,我发现了这个在Scala中实现的联盟:

  def union(a:Set,b:Set):Set = i => a(i)|| b(i)

Set是一个类型的函数:

  type Set = Int =>布尔

现在我明白在Scala中,函数从Int到Boolean映射到这里,而且我进一步了解如何执行此语句:

  a(i)|| b(i)

但我不明白的是'我'在这里是什么。它从何而来?当它找到集合之间的匹配时,它返回true,如果确实如此,我在哪里过滤它? 假设我们有一个名为 SoSet 的对象,它由

给出

  object SoSet {
类型Set = Int =>布尔
val a:Set = ???
val b:Set = ???
def isItem(item:Int)= a(item)|| b(项目)
}

isItem 由 Int =>给出。布尔,它是 Set 。到现在为止还挺好。



但是现在我们只想返回函数 isItem (即一个集)。



因此,我们定义 union 函数(现在没有参数,我们稍后会添加它)。

  object SoSet {
// ..
def union:Set = isItem //返回函数isItem
}

现在让我们重构 isItem 转换为。

  object SoSet {
// ..
def union:Set = {
(item:Int)=>一个(item)|| b(物品)
}
}

让我们移动从对象SoSet 设置a和b 为 def union 的参数。重构项目到 i 。

  object SoSet {
type Set = Int =>布尔
def union(a:Set,b:Set):Set =(i:Int)=> a(i)|| b(i)
}

更新

  val s1 =设置(1,2,3)
val s2 =设置(2,3,4)
val s3 = union(s1,s2)//返回函数.. Int =>布尔=< function1>
s3(2)//调用函数&检查工会中是否存在2


From the question linked here, I found this implementation of Union in Scala:

def union(a: Set, b: Set): Set = i => a(i) || b(i)

And Set is a function of type:

type Set = Int => Boolean

Now I understand that in Scala, a function is mapped from Int to Boolean here, and I further understand how this statement is executed:

a(i) || b(i)

But what I don't understand is what is 'i' here. Where does it come from? And when it finds a match between to sets, it returns true, if it indeed does, where do I filter it?

解决方案

Let say we have object called SoSet given by

object SoSet {
    type Set = Int => Boolean
    val a : Set = ???
    val b : Set = ???
    def isItem(item : Int) = a(item) || b(item)
}

The signature of isItem is given by Int => Boolean which is a Set. So far so good.

But now we just want to return the function isItem (i.e. a Set).

So lets define union function for this (There are no parameters right now. We will add it later).

object SoSet {
    //..
     def union : Set = isItem // returns the function isItem
}

Now lets refactor the isItem into a anonymous function.

object SoSet {
    //..
    def union : Set = {
      (item : Int) => a(item) || b(item)
    }
}

Lets move Set a and b from object SoSet to parameters of def union. Refactor item to i.

object SoSet {
   type Set = Int => Boolean
   def union(a : Set, b : Set) : Set = (i : Int) => a(i) || b(i)
}

UPDATE

 val s1 = Set(1, 2, 3)
 val s2 = Set(2, 3, 4)
 val s3 = union(s1, s2) //  returns the function..  Int => Boolean = <function1>
 s3(2)  // invokes the function & checks if 2 is present in the union

这篇关于斯卡拉的两套联盟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:51