title: An example of functional programming in scala
body: <p>I'm studying scala. It's very promising, thanks to Odersky and all the other authors for their great work.</p>
  
  <p>I took a euler problem (<a href="http://projecteuler.net" rel="noreferrer">http://projecteuler.net/</a>) to have a more-then-minimal example. And I'm trying to go the functional way. So this is not a "please answer me immediatly or my boss will kill me" but a "please if you've got time, can you help a imperative language programmer to take a journey in the functional world?"</p>
  
  <p>Problem: I want a class for poker hands. A poker Hand is composed by a number of Card, from 0 to 5. I'd like to build the list of Cards one and for all, that is: my Hand class will be immutable, if I want to add a card, then I create a new Hand object.
  So I need a collection of Card that can be created as "val", not as var. 
  First step: constructors, one for each number of cards. But Card's collection is handled in each constructor, so I must have it as var!</p>
  
  <p>Here's the code, Card class is simply a Suit and a Value, passed to constructor as a string ("5S" is the 5 of spades):</p>
  
  <pre><code>class Hand(mycards : List[Card]) {
    // this should be val, I guess
    private var cards : List[Card] = {
      if (mycards.length&gt;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 */
  }
  </code></pre>
  
  <p>Do you know how to make it the true functional way?
  Thanks.</p>
  
  <p>PS: if you really want to know, it's problem 54.</p>