2017-02-19 87 views
2

我有一堆函数清理文本并将它们分成单词。最小示例:斯卡拉链函数与和类型不匹配

val txt = "Mary had a @little \nlamb" 
val stopwords = Seq("a") 
def clean(text: String): String = text.replaceAll("\n*\r*", "") 
def tokenize(text: String): Seq[String] = text.split("\\s") 

val cleaned = clean(txt) 
val tokens = tokenize(cleaned) 

此代码按预期工作。但不是真正的惯用。 我希望做到这一点:

clean(txt) andThen tokenize 

但是,编译器会抱怨这与在令牌化功能错误type mismatch; required: Char => ?

我在这里错过了什么?

回答

2

clean返回String。你试图在String实例使用andThen(因为你调用方法clean(txt))和编译器推断它作为PartialFunction[Char, ?](因为WrappedString继承AbstractSeq[Char]它继承PartialFunction[Char, A])。这就是为什么你看到类型不匹配。如果你想撰写两者结合起来,采用ETA-扩大把它们变成功能类型:

val res = clean _ andThen tokenize 
println(res(txt)) 

功能组合工作方式上Scala的功能,而不是方法(有区别),这就是为什么我们有首先将该方法扩展为函数(clean _),然后编译器将能够为我们推断tokenize,而无需手动扩展它。

+1

有趣,我明白了。不知道eta扩展。我有一些阅读要做:)。 – Tim

相关问题