昨日のを Scala で書いてみる

  • そのまま移し変えるのではなくもうちょっといじった(気分で)
  • filterNot が使いたかったけどよく分からなかったのでこのようになった
  • ねむい
import scala.util.matching.Regex

def excludeByDomain(
  excludeUrlHeads :List[Regex], urls :List[String]
) :List[String] = {
  urls.filter{ (url) =>
    var matched = false

    excludeUrlHeads.foreach{ re =>
      if( re.findAllIn(url).toList.size > 0 ){
        matched = true
      }
    }

    matched == false
  }
}

def reMatch(re :Regex, str :String) :Boolean = {
  re.findAllIn(str).toList.size > 0
}

// 除外対象ではない場合 true
def notExclude(excludeUrlHeads :List[Regex], url :String) :Boolean = {
  excludeUrlHeads.filter{ re =>
    reMatch(re, url)
  }.size == 0 // どれにもマッチしていない
}

def excludeByDomainFunctionally(
  excludeUrlHeads :List[Regex], urls :List[String]
) :List[String] = {
  urls.filter{ url =>
    notExclude(excludeUrlHeads, url)
  }
}

// このパターンに先頭一致するものを除外したい
val excludeUrlHeads = List(
  "http://example.jp/"
  , "http://example.org/"
).map{ head => ("^" + head).r }

val urls = List(
  "http://example.com/foo"
  , "http://example.com/foo/bar"
  , "http://example.jp/foo"
  , "http://example.org/foo"
)

println( excludeByDomain(excludeUrlHeads, urls) )
//=> List(http://example.com/foo, http://example.com/foo/bar)

println( excludeByDomainFunctionally(excludeUrlHeads, urls) )
//=> List(http://example.com/foo, http://example.com/foo/bar)