EzDevInfo.com

pattern-matching interview questions

Top pattern-matching frequently asked interview questions

Pattern matching on the beginning of a string in f#

I am trying to match the beginning of strings in f#. Not sure if I have to treat them as a list of characters or what. Any suggestions would be appreciated.

Here is a psuedo code version of what I am trying to do

let text = "The brown fox.."

match text with
| "The"::_ -> true
| "If"::_ -> true
| _ -> false

So, I want to look at the beginning of the string and match. Note I am not matching on a list of strings just wrote the above as an idea of the essence of what I am trying to do.


Source: (StackOverflow)

How to pattern match using regular expression in Scala?

I would like to be able to find a match between the first letter of a word, and one of the letters in a group such as "ABC". In pseudocode, this might look something like:

case Process(word) =>
   word.firstLetter match {
      case([a-c][A-C]) =>
      case _ =>
   }
}

But how do I grab the first letter in Scala instead of Java? How do I express the regular expression properly? Is it possible to do this within a case class?


Source: (StackOverflow)

Advertisements

What is 'Pattern Matching' in functional languages?

I'm reading about functional programming and I've noticed that Pattern Matching is mentioned in many articles as one of the core features of functional languages.

Can someone explain for a Java/C++/JavaScript developer what does it mean?


Source: (StackOverflow)

What does x?.y?.z mean?

The draft spec for Pattern Matching in C# contains the following code example:

Type? v = x?.y?.z; 
if (v.HasValue) {
    var value = v.GetValueOrDefault();     
    // code using value 
} 

I understand that Type? indicates that Type is nullable, but assuming x, y, and z are locals, what does x?.y?.z mean?


Source: (StackOverflow)

Scala: short form of pattern matching that returns Boolean

I found myself writing something like this quite often:

a match {     
  case `b` => // do stuff
  case _ => // do nothing
}

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

if (a matches b) // do stuff

I'm relatively new to Scala, so please pardon, if I'm missing something big :)


Source: (StackOverflow)

How to use switch/case (simple pattern matching) in Scala?

I've found myself stuck on a very trivial thing :-]

I've got an enum:


object Eny extends Enumeration {
  type Eny = Value
  val FOO, BAR, WOOZLE, DOOZLE = Value
}

In a code I have to convert it conditionally to a number (varianr-number correspondence differs on context). I write:


val en = BAR
val num = en match {
  case FOO => 4
  case BAR => 5
  case WOOZLE => 6
  case DOOZLE => 7
}

And this gives me an "unreachable code" compiler error for every branch but whatewer is the first ("case FOO => 4" in this case). What am I doing wrong?


Source: (StackOverflow)

Pattern Matching - Prolog vs. Haskell

This is not a homework question, rather an exam study guide question. What is the difference between pattern matching in Prolog Vs Haskell?

I've done some research and reading up on the theories behind them doesn't really give me a solid understanding between the two. I read that in Prolog, pattern matching is different because it has the ability to unify variables and thus be able to deduce through resolution and spit out the possible answer

eg ?- [a,b] = [a,X]
   X = b

Now I'm not sure how to display pattern matching in Haskell. I know that the same query above shown in Prolog will not work in Haskell because Haskell cannot unify like Prolog. I remember somewhere that to get the same answer in Haskell, you have to explicitly tell it through guards.

I know that I am pretty close to understanding it, but I need someone to break it down Barney style for me so I can FULLY understand it and explain it to a 12 year old. This has been bugging me for quite some time and I can't seem to find a solid explanation.

By the way the example shown above was just to display to you guys what I've learned so far and that I'm actually trying to find an answer. My main question does not relate to the examples above but rather a complete understanding on the difference between the two.


Source: (StackOverflow)

grep in R with a list of patterns

I am trying to use grep to test whether a list of values are present in an array or not, and to output the list of values that are present (the matching patterns). So basically, having an array like this:

**FirstName** *Letter*

Alex      *A1*
Alex      *A6*
Alex      *A7*
Bob       *A1*
Chris     *A9*
Chris     *A6*

And a List of 'Letters' to be found in this array, for example: A1, A9, A6. I would like to check whether a list of 'Letter' is present or not in this array, and if they are I would like the output of unique values to be stored in another file.

The problem is, I don't know how to use grep with multiple patterns. I tried:

matches <- unique (
    grep("A1| A9 | A6", myfile$Letter, value=TRUE, fixed=TRUE)
)

But it gives me 0 matches which is not true.
Do you have any suggestions?
Thank you very much.


Source: (StackOverflow)

Catching multiple exceptions at once in Scala

How to catch multiple exceptions at once in Scala? Is there a better way than in C#: Catch multiple Exceptions at once?


Source: (StackOverflow)

How to override apply in a case class companion

So here's the situation. I want to define a case class like so:

case class A(val s: String)

and I want to define an object to ensure that when I create instances of the class, the value for 's' is always uppercase, like so:

object A {
  def apply(s: String) = new A(s.toUpperCase)
}

However, this doesn't work since Scala is complaining that the apply(s: String) method is defined twice. I understand that the case class syntax will automatically define it for me, but isn't there another way I can achieve this? I'd like to stick with the case class since I want to use it for pattern matching.


Source: (StackOverflow)

Finding matches between high quality and low quality, pixelated images - is it possible ? How?

I have a problem. My company has given me an awfully boring task. We have two databases of dialog boxes. One of these databases contains images of horrific quality, the other very high quality.

Unfortunately, the dialogs of horrific quality contain important mappings to other info.

I have been tasked with, manually, going through all the bad images and matching them to good images.

Would it be possible to automate this process to any degree? Here is an example of two dialog boxes (randomly pulled from Google images) :

Good quality image

Bad Quality image

So I am currently trying to write a program in C# to pull these photos from the database, cycle through them, find the ones with common shapes, and return theird IDs. What are my best options here ?


Source: (StackOverflow)

Explaining pattern matching vs switch

I have been trying to explain the difference between switch statements and pattern matching(F#) to a couple of people but I haven't really been able to explain it well..most of the time they just look at me and say "so why don't you just use if..then..else".

How would you explain it to them?

EDIT! Thanks everyone for the great answers, I really wish I could mark multiple right answers.


Source: (StackOverflow)

How to use SIFT algorithm to compute how similiar two images are?

I have used the SIFT implementation of Andrea Vedaldi, to calculate the sift descriptors of two similar images (the second image is actually a zoomed in picture of the same object from a different angle).

Now I am not able to figure out how to compare the descriptors to tell how similar the images are?

I know that this question is not answerable unless you have actually played with these sort of things before, but I thought that somebody who has done this before might know this, so I posted the question.

the little I did to generate the descriptors:

>> i=imread('p1.jpg');
>> j=imread('p2.jpg');
>> i=rgb2gray(i);
>> j=rgb2gray(j);
>> [a, b]=sift(i);  % a has the frames and b has the descriptors
>> [c, d]=sift(j);

Source: (StackOverflow)

Pattern matching with conjunctions (PatternA AND PatternB)

Scala has a language feature to support disjunctions in pattern matching ('Pattern Alternatives'):

x match {
    case _: String | _: Int => 
    case _ =>
}

However, I often need to trigger an action if the scrutinee satisfies PatternA and PatternB (conjunction.)

I created a pattern combinator '&&' that adds this capability. Three little lines that really remind me why I love Scala!

// Splitter to apply two pattern matches on the same scrutinee.
object && {
  def unapply[A](a: A) = Some((a, a))
}

// Extractor object matching first character.
object StartsWith {
  def unapply(s: String) = s.headOption
}

// Extractor object matching last character.
object EndsWith {
  def unapply(s: String) = s.reverse.headOption
}

// Extractor object matching length.
object Length {
  def unapply(s: String) = Some(s.length)
}

"foo" match {
  case StartsWith('f') && EndsWith('f') => "f.*f"
  case StartsWith('f') && EndsWith(e) && Length(3) if "aeiou".contains(e) => "f..[aeiou]"
  case _ => "_"
}

Points for discussion

  1. Is there an existing way to do this?
  2. Are there problems with this approach?
  3. Are there other useful combinators that could be created with this approach? (for example, Not)
  4. Should such a combinator be added to the standard library?

UPDATE I've just been asked how the compiler interprets case A && B && C. These are infix operator patterns (Section 8.1.9 of the Scala Reference). You could also express this with normal extract patterns (8.1.7) as &&(&&(A, B), C). Notice how the expressions are associated left to right, as per normal infix operator method calls like Boolean#&& in val b = true && false && true.


Source: (StackOverflow)

Does PostgreSQL support "accent insensitive" collations?

In Microsoft SQL Server, it's possible to specify an "accent insensitive" collation (for a database, table or column), which means that it's possible for a query like

SELECT * FROM users WHERE name LIKE 'João'

to find a row with a Joao name.

I know that it's possible to strip accents from strings in PostgreSQL using the unaccent_string contrib function, but I'm wondering if PostgreSQL supports these "accent insensitive" collations so the SELECT above would work.


Source: (StackOverflow)