/*
   Copyright 2010 Aaron J. Radke

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package cc.drx

//-----Pluck typeclass
trait Pluck[A,B]{
  /**Interface*/
  def pluckAll(a:A):Iterator[B]

  final def pluck(a:A):Option[B] = {
    val it = pluckAll(a)
    if(it.hasNext) Some(it.next()) else None
  }
}
object Pluck{
  //String -> f(matcher,transformer) -> List[A]

  def apply[B](regex:Regex, f:Regex.Match => B) = PluckRegex[B](regex,f)
  def apply(regex:Regex, i:Int=1)               = PluckRegex[String](regex, m => m group 1)
  def apply(regex:Regex, i:Int,j:Int)           = PluckRegex[(String,String)](regex, m => (m group i, m group j))

  // def apply[B](regex:Regex)(implicit p:Parsable[B]) = PluckRegex[B](regex, m => Parse[B](m group 1) )

  case class PluckRegex[B](regex:Regex, f:Regex.Match => B) extends Pluck[String,B]{
    def pluckAll(a:String):Iterator[B] = regex findAllMatchIn a map f
  }
  /*
  case class PluckSep(sep:Data.Sep) extends Pluck[String,String]{
    def pluckAll(a:String):Iterator[String] = (a split sep.value).iterator
  }
  */

}