Skip to content

Instantly share code, notes, and snippets.

@jvrdev
Created August 12, 2015 10:54
Show Gist options
  • Select an option

  • Save jvrdev/0654be7082f1874751bf to your computer and use it in GitHub Desktop.

Select an option

Save jvrdev/0654be7082f1874751bf to your computer and use it in GitHub Desktop.
let matches (pattern : string) (x : string) : bool =
let rec matchesL pattern x =
match pattern, x with
| [], [] | ['?'], [] | ['*'], []-> true
| '?'::pTail, xHead::xTail -> matchesL pTail xTail || matchesL pTail x
| '*'::pTail, xHead::xTail -> matchesL pTail xTail || matchesL pTail x || matchesL pattern xTail
| pHead::pTail, xHead::xTail when pHead = xHead -> matchesL pTail xTail
| _ -> false
matchesL (Seq.toList pattern) (Seq.toList x)
let findMatches (pattern : string) (xs : seq<string>) : seq<string> =
Seq.where (matches pattern) xs
@freskog
Copy link
Copy Markdown

freskog commented Aug 12, 2015

This is the equivalent Scala version.

  def matches(p:String)(s:String):Boolean = {
    def matchesL(pattern: List[Char])(x: List[Char]): Boolean = (pattern, x) match {
      case (Nil, Nil) | (List('?'), Nil) | (List('*'), Nil) => true
      case ('?' :: pTail, xHead :: xTail) => matchesL(pTail)(xTail) || matchesL(pTail)(x)
      case ('*' :: pTail, xHead :: xTail) => matchesL(pTail)(xTail) || matchesL(pTail)(x) || matchesL(pattern)(xTail)
      case (pHead :: pTail, xHead :: xTail) if pHead == xHead => matchesL(pTail)(xTail)
      case _ => false
    }
    matchesL(p.toList)(s.toList)
  }

  def findMatches(pattern:String, candidates:List[String]):List[String] =
    candidates.filter(matches(pattern))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment