2014-12-13 39 views
1

我工作的一些功能,需要一個元素,與此元素返回單例類,參數化類型,如下圖所示:Scala和設置的詮釋

def singletonSet(elem: Int): Set = 
    e => elem == e 

但斯卡拉REPL發送信號指示這樣的問題:

scala> def singletonSet(elem: Int): Set = 
    |  e => elem == e 
<console>:7: error: type Set takes type parameters 
     def singletonSet(elem: Int): Set = 

我曾嘗試爲INT集添加一個類型,但它並不能幫助

def singletonSet(elem: Int): Set[Int] = 
    e => elem == e 

scala> def singletonSet(elem: Int): Set[Int] = 
    |  e => elem == e 
<console>:8: error: type mismatch; 
found : Int => Boolean 
required: Set[Int] 
      e => elem == e 

坦白地說,我不知道我的錯誤是鋪設,我使用2.11.4斯卡拉:)

編輯:

類似的問題,我此行的代碼:

def union(s: Set[Int], t: Set[Int]): Set[Int] = (e: Int) => s(e) || t(e) 
<console>:7: error: type mismatch; 
found : Int => Boolean 
required: Set[Int] 
     def union(s: Set[Int], t: Set[Int]): Set[Int] = (e: Int) => s(e) || t(e) 

這會導致類似的錯誤。

編輯:

我忘了

type Set = Int => Boolean 
+0

'Set [Int]'是'Int => Boolean'的子類型,所以你的直覺是相反的。 – 2014-12-13 18:58:10

回答

0

以下是一個比較 - 從而返回類型是布爾

elem == e 

你想要什麼:

Set(elem) 

所以:

scala> def singletonSet(elem: Int): Set[Int] = Set(elem) 
singletonSet: (elem: Int)Set[Int] 
1

試試這個:

def singletonSet(elem: Int): Set[Int] = Set(elem) 

這樣,您將調用Set.apply法的e單要素創建一個Set

你的直覺是相反的Int=>BooleanSet[Int]

+0

不能編譯 – javadba 2014-12-14 00:24:37

+0

@javadba謝謝。 – 2014-12-14 07:34:57

1

您需要提供一個類型參數,使其通用

def singletonSet[A](a: => A): Set[A] = Set(a) 

=>避免argument元素進行評估將它放在Set之前。


順便說一句,你想實現什麼是完全的Applicative類型類的point方法。

Here's它的scalaz版本。

使用scalaz,你可以這樣做

1.point[Option] // Some(1) 
1.point[Set] // Set(1) -- this requires scalaz-outlaws 
1.point[List] // List(1) 

請注意,因爲Set不被認爲是一個正確的Applicative(也不是Functor),其Applicative實例的實現是由scalaz-outlaws項目提供。

+0

你爲什麼使用名字叫'a'的參數? – MC2DX 2014-12-13 19:40:36

+0

您不想將其放入容器中以引起評價。或者如果你想,只要刪除=> – 2014-12-13 20:52:33