Scala pattern matching on sequences other than Lists

As of the ides of March 2012, this works in 2.10+: def doMatch(seq: Seq[Int]): Unit = seq match { case last +: Seq() => println(“Final element.”) case head +: tail => println(“Recursing…”); doMatch(tail) } //> doMatch: (seq: Seq[Int])Unit doMatch(List(1, 2)) //> Recursing… //| Final element. More generally, two different head/tail and init/last decomposition objects mirroring … Read more

Check if string ends with certain pattern

This is really simple, the String object has an endsWith method. From your question it seems like you want either /, , or . as the delimiter set. So: String str = “This.is.a.great.place.to.work.”; if (str.endsWith(“.work.”) || str.endsWith(“/work/”) || str.endsWith(“,work,”)) // … You can also do this with the matches method and a fairly simple regex: … Read more

What does x?.y?.z mean?

Be aware that this language feature is only available in C# 6 and later. It’s effectively the equivalent of: x == null ? null : x.y == null ? null : x.y.z In other words, it’s a “safe” way to do x.y.z, where any of the properties along the way might be null. Also related … Read more

What is the use of Pattern.quote method?

\Q means “start of literal text” (i.e. regex “open quote”) \E means “end of literal text” (i.e. regex “close quote”) Calling the Pattern.quote() method wraps the string in \Q…\E, which turns the text is into a regex literal. For example, Pattern.quote(“.*”) would match a dot and then an asterisk: System.out.println(“foo”.matches(“.*”)); // true System.out.println(“foo”.matches(Pattern.quote(“.*”))); // false … Read more

Pattern matching on the beginning of a string in f#

Parameterized active patterns to the rescue! let (|Prefix|_|) (p:string) (s:string) = if s.StartsWith(p) then Some(s.Substring(p.Length)) else None match “Hello world” with | Prefix “The” rest -> printfn “Started with ‘The’, rest is %s” rest | Prefix “Hello” rest -> printfn “Started with ‘Hello’, rest is %s” rest | _ -> printfn “neither”