scala中函数式编程的一个例子
我正在学习斯卡拉.感谢Odersky和所有其他作者的出色工作,这是非常有前途的.
我把一个欧拉问题(http://projecteuler.net/)带到了一个更加极小的例子.而我正试图以功能的方式.所以这不是“请立即回答我,否则我的老板会杀了我”,但是“如果你有时间,请帮助一位势在必行的语言程序员去实现功能性世界吗?” 问题:我想要一个扑克牌课.一个扑克之手是由一些卡片组成的,从0到5.我想建立一个卡片列表,这就是:我的Hand类是不可变的,如果我想添加一张卡片,那么我创建了一个新的Hand对象. 这是代码,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,d : String) = this(a,b,c,d,null) def this(a : String,c : String) = this(a,b : String) = this(a,null) def this(a : String) = this(a,null) def this() = this(Nil) /* removed */ } 你知道如何使它成为真正的功能方式吗? PS:如果你真的想知道,那就是问题54. 解决方法
我的答案不是关于scala的功能方面,但你的代码很可能使用scala sugar写:
class Hand(val mycards: List[Card]) { require (mycards.size <= 5,"can't be more than five cards") def this(input: String*) = { this(input.map(c => new Card(c)).toList) } } input:辅助构造函数中的String *表示您可以拥有可变数量的参数(甚至数千个字符串). class Hand(val mycards:List [Card]){… 是平等的 class Hand(cards: List[Card]) { val mycards = cards ... 从现在开始,如果您将尝试创建五张以上的卡,您将获得java.lang.IllegalArgumentException: scala> class Card(s: String) {println("Im a :"+s)} defined class Card scala> new Hand("one","two","three","four","five","six") Im a :one Im a :two Im a :three Im a :four Im a :five Im a :six java.lang.IllegalArgumentException: requirement failed: can't be more than five card at scala.Predef$.require(Predef.scala:157) at Hand.<init>(<console>:9) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |