我是新手,我会尽量保持清醒。这是关于odersky scala课程。
我在下面有这个代码。我理解这是一个别名类型来定义Scala集,这与您在Scala中定义Set的传统方式(即Scala集合)不同。在这个类型的别名中,你给它一个整数,如果该项包含在Set中,则返回true(不知何故)。
type Set = Int => Boolean
现在我有了这段代码,它返回了我期待的结果。
val a = Set("element is contained in set")
type Set = Int => Boolean
a.contains("element is contained in set")
a.contains("element IS NOT contained in set")
结果是:
a: scala.collection.immutable.Set[String] = Set(element is contained in set)
defined type alias Set
res0: Boolean = true
res1: Boolean = false
res2: scala.collection.immutable.Set[String] = Set(element is contained in set)
大!现在我在代码中引入一行。
val a = Set("element is contained in set")
type Set = Int => Boolean
a.contains("element is contained in set")
a.contains("element IS NOT contained in set")
**def custom_fc(x:Double): Set[String] = Set(x.toString)**
我收到错误:
Error:(8, 24) A$A235.this.Set does not take type parameters
def custom_fc(x:Double): Set[String] = Set(x.toString)
Error:(38, 97) inst$A$A.Set does not take type parameters
println("custom_fc: " + MacroPrinter211.printGeneric({import inst$A$A._ ;def `custom_fc(x:Double): Set[String] = Set(x.toString) }).replace("inst$A$A.", ""))`
为什么?在这一行中,我只是试图定义一个常规的fc(即custom_fc),将Int作为输入并返回传统的scala数据结构Set [String]
type Set = Int => Boolean
**def custom_fc(x:Double): Set[String] = Set(x.toString)**
为什么我的自定义fc定义会干扰之前的别名? 我的custom_fc是
custom_fc(x:Double): scala.collection.immutable.Set[String] =
scala.collection.immutable.Set(x.toString)
谢谢
PS。一种使用Type Set = Int => Boolean
val belowNegFive: Set = (i) => i < -5
belowNegFive(10)
如果elem 10属于低于-5的数字组,则返回bool dependinf。
答案 0 :(得分:1)
这是发生了什么。
val a = Set("element is contained in set") // a is old library Set()
type Set = Int => Boolean // alias now hides library Set()
a.contains("element is contained in set") // a is still old library
a.contains("element IS NOT contained in set") // and works like it should
def custom_fc(x:Double): Set[String] = Set(x.toString) // WRONG
// new Set alias works different from old library Set()
课程的重点是使用函数。 Set
别名是一个函数定义:Int => Boolean
,即Int
并返回Boolean
。
新的Set
别名与Set
集合非常不同,无法以相同的方式使用。 Set
别名似乎只是模仿集合,因为您可以查询其内容&#34;以相同的方式,但仅在使用Int
值时。即便如此,初始化方法也不同。
val libSet: collection.Set[Int] = Set(7) // initialize with a 7
type Set = Int => Boolean
val newSet: Set = (x:Int) => x == 7 // initialize with a 7
libSet(7) // true
libSet(4) // false
newSet(7) // true
newSet(4) // false
库集合适用于其他类型,但Set
别名只需Int
并返回Boolean
。新Set
是函数定义的类型别名。新Set
的一个实例是一个仅模仿真实Set
所做内容的一小部分的函数。
答案 1 :(得分:0)
所以你显然已经覆盖了已经存在的Set别名。你可以通过评论中提到的方法解决这个问题,准确指出你的意思。
def custom_fc(x:Int): scala.collection.immutable.Set[String] = Set(x.toString)
另请注意,您的类型别名没有做任何事情。您的来电a("element is contained in set")
a("element IS NOT contained in set")
只是在a上调用apply方法,这与执行a.apply(...)
和a.contains(...)
相同。为了让自己更轻松,整体上不那么混乱,可能会更改名称为Contains
?
要查看正在使用您的设置的示例,请转到此处...
val setBeingUsed: Set = Set(1).contains
setBeingUsed(1) // true
接受Int并返回布尔值的方法可以分配类型Set
,因为您将该类型别名化。然后我们可以调用我们使用类型Set
创建的val,并且基本上与在集合上调用contains相同。