Created
          July 6, 2010 11:48 
        
      - 
      
- 
        Save yuroyoro/465280 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // implict conversionやPartialFunctionを駆使した奇妙なFizzBuzz | |
| // PartialFunction[A,B]を "A --> B"のように書けるようにしておく | |
| type -->[A,B] = PartialFunction[A,B] | |
| // FizzBuzz用のPartailFunctionを生成するユーティリティ | |
| def toPF[A]( r:String )( f: A => Boolean): A --> String = | |
| { case v if f(v) => r } | |
| // FizzBuzzできるSeq | |
| class FizzBuzzSeq[A]( theSeq:Seq[A] ) extends Seq[A] { | |
| def apply(idx: Int):A = theSeq( idx ) | |
| def length = theSeq.length | |
| def iterator = theSeq.iterator | |
| val defaultPF:A --> String = { case v => v.toString } | |
| def fizzBuzz( pfSeq:A --> String * ) = | |
| theSeq.collect( ( pfSeq :+ defaultPF ) reduceLeft { (a,b) => a orElse b } ) | |
| } | |
| // implicit conversionでSeq[A]をFizzBuzzSeq[A]にする | |
| implicit def seqToFizzBuzz[A]( theSeq:Seq[A] ) = new FizzBuzzSeq( theSeq ) | |
| // PatrialFunctionを渡してFizzBuzz | |
| // implicit conversionで(1 to 100)はFizzBuzzSeq[Int]になる | |
| (1 to 100 ).fizzBuzz( | |
| toPF( "FizzBuzz") { v => v % 15 == 0 }, | |
| toPF( "Fizz") { v => v % 3 == 0 }, | |
| toPF( "Buzz") { v => v % 5 == 0 } | |
| ).foreach{ println } | |
| // こう書いても同じ | |
| (1 to 100 ).fizzBuzz( | |
| { case v if v % 15 == 0 => "FizzBuzz" }, | |
| { case v if v % 3 == 0 => "Fizz" }, | |
| { case v if v % 5 == 0 => "Buzz" } | |
| ).foreach{ println } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment