2012-02-24 187 views

回答

3

功能这是指定功能的一种方式。函数是将一个或多个参数作为输入并返回输出的东西。您可以使用=>符号指定函数的一种方法。

s: String => s.length == 4 // a function that takes a String called s as input 
          // and returns a Boolean (true if the length of s is 4 
          // false otherwise) 

在scala中,您可以使用像使用整数或字符串或任何其他类型的基本数据类型的函数。

您可以将它们分配给变量:

scala> val f = (s: String) => s.length==4 // assigning our function to f 
f: String => Boolean = <function1> 

scala> f("abcd") // ...and using it 
res1: Boolean = true 

,你可以将它们作为参数,其它函数或方法:你说的remove方法

scala> val thrill = List("foo", "bar", "baz", "bazz") 
thrill: List[java.lang.String] = List(foo, bar, baz, bazz) 

scala> thrill.remove(s => s.length == 4) 
warning: there were 1 deprecation warnings; re-run with -deprecation for detail 

res2: List[java.lang.String] = List(foo, bar, baz) 

这里:“应用这个函数s => s.length == 4到列表中的每个元素,并删除所有元素,其中该函数返回true“

顺便说一下,请注意,remove已被弃用。建议的替代方案是filterNot

scala> thrill.filterNot(s => s.length == 4) 
res3: List[java.lang.String] = List(foo, bar, baz) 
+0

真棒,谢谢: ) – LuckyLuke 2012-02-24 21:37:44

+0

删除不是一个函数,它是一种方法。这个区别在Scala中非常重要。 (例如函数是对象,方法不是。) – 2012-02-25 00:35:26

+0

@JörgW Mittag yikes!你是对的!修复了我的答案,非常感谢您的接受! – 2012-02-25 14:46:13

2

表达

s => s.length == 4 

表示一个函数,它采用一个字符串(我猜)和返回基于它是否具有长度为4

val f = s => s.length == 4 
println(f("five")) //prints "true" 
println(f("six")) //prints "false" 

s =>的布尔值部分只是声明函数的参数名称(在这种情况下,只有一个:s

1

这就是说“运行功能s => s.length == 4在所有项目上的快感,并删除任何地方的函数返回true。”从逻辑上讲,该函数必须将thrill中包含的单个项目作为参数,并且必须返回一个布尔值(true或false)。

scala语法s => ...表示lambda函数 - 一种简写函数,其中在许多情况下函数的参数和返回类型被推断。例如,在这种情况下,编译器足够聪明,知道如果快感包含字符串,则s必须是字符串。同样,它可以以静态类型的方式确认返回值(s.length == 4)是一个布尔值,并且满足布尔返回值的要求。

总之:把它看成定义为boolean f(String s) { return s.length == 4; }

1

我相信所有的以下都是彼此相同(虽然我是斯卡拉福利局也随时提供勘误的内容)

thrill.remove((s:String) => s.length == 4) 
thrill.remove(s => s.length == 4) 
thrill.remove(_.length == 4) 
+0

这里使用'return'错误(在REPL中尝试它,你会得到'error:return outside method definition')。你可能会喜欢使用'Function1'特性来包含定义没有糖的函数...... :) – 2012-02-24 21:59:53

+0

thx,我稍后再尝试FUnction1,现在我拿出了有问题的回报。我没有在这里安装REPL,所以我在尝试http://ideone.com/,它不起作用 - 现在我知道为什么 – 2012-02-24 22:22:23