Wednesday, November 2, 2011

Chewy code : scala TicTacToe part 4

Authored by Win Myo Htet


The print statements have helped me see a lot of the moving parts, enhanced the performance and demystified some of the code as stated in Part 3. Especially, the yield line in whoWon method. Even then, it still takes a while for me to understand won_? which is called inside whoWon.

private def won_?(moves: Seq[Option[Move]], m: Move): Boolean = moves.foldLeft(List(0)) {
    case (count :: rest, Some(`m`)) => count + 1 :: rest
    case (counts, _) => 0 :: counts
  }.max >= WinCount

The fault lies with my untrained eye for Scala reading and the column alignment of "count ::" and "counts," and the new introduction of back tick, Some(`m`), does not help too. At first, I don't even know why I cannot read the code. I keep staring at it and even the print statements are not helping. Then, I am able to analyze the construction pattern after a while. I came to realize that I don't know back tick and I am wondering how else the comma "," works in List. I know the con(constructor) "::" usage but not comma ",". Then, the eureka moment set in(please don't visualize me doing anything crazy, I just sit there before the screen and enjoy the moment.). Comma "," works like comma does and I started seeing the (foldLeftSeedValue,foldLeftElement) pattern. From there, the mysteries start breaking away.

For the first case match, foldLeftSeedValue is count :: rest, which deduced to List,  and foldLeftElement is Some(`m`). Since we are doing the matching here, we are matching foldLeftElement. The back tick allow us to refer back to the variable out of this code segment scope, thus we are matching foldLeftElement, which is in the form of Option[Move], to see if it is the same as object m of Move from the parameter, boxed inside Some. If it is, then we are passing over the expression Int::List while increasing the count.

If the foldLeftElement is not Some(`m`) or rather correctly, for anything else, _, the second case will be triggered. 0 is prepended to the List returned.

I still don't like how the Int object count is created in the thin air tho. Anyway, at the end max looks for the largest element in the List and compare. Thus, we come to the completion of understanding Oleg's Tic Tac Toe code. I have done a fork version of it with my glorified print statement and modification here. Again, I thanks Oleg for such an awesome Scala code and permission to blog about it. I hope to be able to write like this soon. Yeh, the code is quite chewy.





Authored by Win Myo Htet

1 comment:

  1. Merkur 15c Safety Razor - Barber Pole - Deccasino
    Merkur 15C Safety Razor septcasino.com - Merkur deccasino - 15C for Barber Pole is the perfect introduction to the Merkur jancasino.com Safety 오래된 토토 사이트 Razor.

    ReplyDelete