小编Jam*_*irk的帖子

如何编写递归匿名函数?

在我继续努力学习scala的过程中,我正在通过Odersky的'示例Scala'和第一类函数的章节,关于匿名函数的部分避免了递归匿名函数的情况.我有一个似乎有效的解决方案.我很好奇是否有更好的答案.

从pdf:Code来展示更高阶的功能

def sum(f: Int => Int, a: Int, b: Int): Int =
  if (a > b) 0 else f(a) + sum(f, a + 1, b)

def id(x: Int): Int = x
def square(x: Int): Int = x * x
def powerOfTwo(x: Int): Int = if (x == 0) 1 else 2 * powerOfTwo(x-1)

def sumInts(a: Int, b: Int): Int = sum(id, a, b)
def sumSquares(a: Int, b: Int): Int = sum(square, a, b)
def sumPowersOfTwo(a: Int, b: Int): Int …
Run Code Online (Sandbox Code Playgroud)

recursion scala anonymous-function

6
推荐指数
1
解决办法
2271
查看次数

如何在对象上调用'!='方法?

我刚开始玩scala并且一直使用Michel Schinz的"Scala By Example"(http://www.scala-lang.org/node/198)作为起点.在特征段中,我尝试使用反射/方法调用来测试特征,并希望测试所有比较运算符.我用名称修改来解决问题,并在NameTransformer中为运营商找到了解决方案.但是,在我看来,它不会转换为等效函数,如<,<=,>,> =,等于.我想知道是否有办法调用!=很像我没有找到的其他运营商?

从pdf:

trait ord {
def < (that:Any):Boolean
def <= (that:Any):Boolean = (this < that) || (this == that)
def > (that:Any):Boolean = !(this <= that)
def >= (that:Any):Boolean = !(this < that)
}

class Date(y:Int, m:Int, d:Int) extends ord{
def year = y
def month = m
def day = d

override def toString():String = year + "-" + month + "-" + day

override def equals(that:Any): Boolean =
  that.isInstanceOf[Date] && {
    val …
Run Code Online (Sandbox Code Playgroud)

scala scala-2.8

3
推荐指数
1
解决办法
204
查看次数

标签 统计

scala ×2

anonymous-function ×1

recursion ×1

scala-2.8 ×1