Functional Programming Principles in Scala
这次的作业叫做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