Martin Odersky Scala编程公开课 第三周作业

Functional Programming Principles in Scala 
by Martin Odersky

这次的作业叫做Object-Oriented Sets。要完成一个完整的类,实现取最大值、排序等方法。由于是函数式编程,这些的实现方法和以往我知道的完全不一样。

总结

TweetSet有两个子类,Empty和NonEmpty,使用BFT实现。有一点比较惊奇的是父类的方法可以创建一个子类的对象,以往并没有认识到这一点。
在方法的实现上,filter和mostRetweeted都需要使用辅助方法(acc)来做递归。
类似于contains的实现方法,很巧妙的对类进行了遍历。
有的方法需要在两个子类里面以不同的方法实现。对于把一个类分成父类和两个子类这一点,我的感觉是为了最大程度的把子类的公共部分抽象出来,杀鸡用了牛刀。
我的实现里面,mostRetweeted调用了mostAcc,同时传递了一个新建的Tweet。为了更优美应该分别在两个子类里面实现。
程序优化很少,感觉运行效率很低,很奇怪有些公司用scala来运营网站等。

我的程序
package objsets

import common._
import TweetReader._

/**
 * A class to represent tweets.
 */
class Tweet(val user: String, val text: String, val retweets: Int) {
  override def toString: String =
    "User: " + user + "\n" +
    "Text: " + text + " [" + retweets + "]"
}

/**
 * This represents a set of objects of type `Tweet` in the form of a binary search
 * tree. Every branch in the tree has two children (two `TweetSet`s). There is an
 * invariant which always holds: for every branch `b`, all elements in the left
 * subtree are smaller than the tweet at `b`. The eleemnts in the right subtree are
 * larger.
 *
 * Note that the above structure requires us to be able to compare two tweets (we
 * need to be able to say which of two tweets is larger, or if they are equal). In
 * this implementation, the equality / order of tweets is based on the tweet's text
 * (see `def incl`). Hence, a `TweetSet` could not
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值