【发布时间】:2011-10-23 21:10:13
【问题描述】:
我正在学习 scala。非常有希望,感谢 Odersky 和所有其他作者的出色工作。
我拿了一个欧拉问题 (http://projecteuler.net/) 来举一个更简单的例子。而且我正在尝试采用功能性方式。所以这不是“请立即回答我,否则我的老板会杀了我”,而是“如果你有时间,你能帮助命令式语言程序员踏上函数式世界的旅程吗?”
问题:我想要一门扑克牌课程。扑克手由许多卡片组成,从 0 到 5。我想一劳永逸地构建卡片列表,即:我的 Hand 类将是不可变的,如果我想添加一张卡片,那么我创建了一个新的 Hand 对象。 所以我需要一个可以创建为“val”而不是 var 的 Card 集合。 第一步:构造函数,每张卡片一个。但是 Card 的集合是在每个构造函数中处理的,所以我必须将它作为 var!
代码如下,Card 类只是一个 Suit 和一个 Value,作为字符串传递给构造函数(“5S”是黑桃 5):
class Hand(mycards : List[Card]) {
// this should be val, I guess
private var cards : List[Card] = {
if (mycards.length>5)
throw new IllegalArgumentException(
"Illegal number of cards: " + mycards.length);
sortCards(mycards)
}
// full hand constructor
def this(a : String, b : String, c : String, d : String, e : String) = {
this(Nil)
// assign cards
val cardBuffer = new ListBuffer[Card]()
if ( a!=null ) cardBuffer += new Card(a)
if ( b!=null ) cardBuffer += new Card(b)
if ( c!=null ) cardBuffer += new Card(c)
if ( d!=null ) cardBuffer += new Card(d)
if ( e!=null ) cardBuffer += new Card(e)
cards = sortCards(cardBuffer.toList)
}
// hand with less then 5 cards
def this(a : String, b : String, c : String, d : String) = this(a,b,c,d,null)
def this(a : String, b : String, c : String) = this(a, b, c, null)
def this(a : String, b : String) = this(a, b, null)
def this(a : String) = this(a, null)
def this() = this(Nil)
/* removed */
}
您知道如何使其成为真正的实用方式吗? 谢谢。
PS:如果你真的想知道,那就是问题 54。
【问题讨论】:
-
通常,
null在功能上是不需要的。对于这种情况,Scala 使用Optionmonad(Haskell 有Maybe)。 Option tutorial -
在主构造函数中添加了 sordCard(),感谢@Rotsor 的帮助。
标签: scala functional-programming