pattern-matching

In Scala, how to test the type of an 'Any' object against a type with type parameter?

和自甴很熟 提交于 2019-12-05 19:26:05
I am trying to get a type-safe way of converting the result of parsing a JSON string. I want to check whether a field is Map[String, any] or a plain string. My first attempt is def test(x:Any) = { x match { case m:Map[String,Any] => ... ... } This causes "non-variable type argument String in type pattern Map[String,Any] is unchecked since it is eliminated by erasure" Looking through the document of TypeTag and ClassTag, I could not find a good way to accomplish that. The following code does not cause the warning, but I wonder why it works. type StringMap = Map[String,Any] def test(x:Any) = { x

Scala pattern matching referencing

陌路散爱 提交于 2019-12-05 19:23:39
When pattern matching case classes how do you actually refer to the class which it was matched to? Here's an example to show what I mean: sealed trait Value case class A(n: Int) extends Value v match { case A(x) => doSomething(A); } Where v is of type value and doSomething takes an parameter of type A , not Value . Do this v match { case a @ A(x) => doSomething(a) } @ is called Pattern Binder (Refer § 8.1.3). From the reference: A pattern binder x@p consists of a pattern variable x and a pattern p. The type of the variable x is the static type T of the pattern p. This pattern matches any value

modifying a field while pattern matching on it

蓝咒 提交于 2019-12-05 18:47:39
I tried my hands at Rust for the first time today (writing a XML tokenizer), and naturally don’t understand everything: I have a struct with field that can take an enum value: enum State { Outside, InATag(~str) } struct Tokenizer { state: State } In a impl Tokenizer , I want to match on the current state, and change it in some cases, however this always gives a use of moved value error. H to access and/or declare the state field so that I can match on it and change its value inside a match branch? Sorry for the confusion, I meant to change the Tokenizer’s state field, not the state’s String

Suggestion for solving fragile pattern matching

谁都会走 提交于 2019-12-05 18:04:27
I often need to match a tuple of values that should have the same constructor. The catchall _,_ always winds-up at the end. This of course is fragile, any additional constructor added to the type will compile perfectly fine. My current thoughts are to have matches that connect the first but not second argument. But, is there any other options? For example, type data = | States of int array | Chars of (char list) array let median a b = match a,b with | States xs, States ys -> assert( (Array.length xs) = (Array.length ys) ); States (Array.init (Array.length xs) (fun i -> xs.(i) lor ys.(i))) |

Regex to match Image Url

 ̄綄美尐妖づ 提交于 2019-12-05 17:57:24
I am trying to get a simple regex to verify that a URL contains the ending figures var testRegex = /^https?:\/\/(?:[a-z\-]+\.)+[a-z]{2,6}(?:\/[^\/#?]+)+\.(?:jpe?g|gif|png)$/; var imageUrl = "http://stackoverflow.com/questions/406192/how-to-get-the-current-url-in-jquery"; if (testRegex.test(imageUrl)) { alert('Not Match'); } And this should trigger alert('Not Match'); and it doesn't ? See http://jsfiddle.net/UgfKn/ What's going on ? do you mean: if (!testRegex.test(imageUrl)) { alert('Not Match'); } testRegex.test will evaluate to True if testRegex DOES match. ie if (testRegex.test(imageUrl)) {

Implicit parameters won't work on unapply. How to hide ubiquitous parameters from extractors?

此生再无相见时 提交于 2019-12-05 16:15:28
Apparently unapply/unapplySeq in extractor objects do not support implicit parameters. Assuming here an interesting parameter a, and a disturbingly ubiquitous parameter b that would be nice to hide away, when extracting c. [ EDIT ]: It appears something was broken in my intellij/scala-plugin installation that caused this. I cannot explain. I was having numerous strange problems with my intellij lately. After reinstalling, I can no longer reprodce my problem. Confirmed that unapply/unapplySeq do allow for implicit parameters! Thanks for your help. This does not work (**EDIT :yes, it does):**

Scala - how to pattern match when chaining two implicit conversions?

╄→гoц情女王★ 提交于 2019-12-05 14:53:14
I wrote a method to parse Metrics data and at first faced a problem with the type of transactionMap which is a java.util.Map . And I solved it using JavaConverters. def parseMetrics(metric: Metric) = { import scala.collection.JavaConverters._ metric.transactionMap.asScala.values.map { case false => "N" case true => "Y" }.toList But after that I got an error while pattern matching true and false values: pattern type is incompatible with expected type, found: Boolean, required: java.lang.Boolean As far as I understand Scala does not chain two implicit conversions. Is there a way to fix it using

How to perform pattern matching with vararg case classes?

≯℡__Kan透↙ 提交于 2019-12-05 13:44:33
问题 I have a set of case classes like this abstract class Shape case class Rectangle(width: Int, height: Int) extends Shape case class Location(x: Int, y: Int, shape: Shape) extends Shape case class Circle(radius: Int) extends Shape case class Group(shape: Shape*) extends Shape where basically Group is an array of shapes. I need to define a size method for computing sizes for rectangle, circle and location its straightforward just return one. But i am having difficulty for Group. object size

Is there any guarantee about the evaluation order within a pattern match?

ぃ、小莉子 提交于 2019-12-05 13:11:56
问题 The following (&&) :: Bool -> Bool -> Bool False && _ = False True && False = False True && True = True has the desired short-circuit property False && undefined ≡ False . The first clause, which is non-strict in the right argument, is guaranteed to be checked before anything else is tried. Apparently, it still works if I change the order and even uncurry the function both :: (Bool,Bool) -> Bool both (True,False) = False both (True, True) = True both (False, _) = False Prelude> both (False,

Restrict Pattern Matching to Subset of Constructors

孤街浪徒 提交于 2019-12-05 12:57:58
Say I have the following: data Type = StringType | IntType | FloatType data Op = Add Type | Subtract Type I'd like to constrain the possible types under Subtract , such that it only allows for int or float. In other words, patternMatch :: Op -> () patternMatch (Add StringType) = () patternMatch (Add IntType) = () patternMatch (Add FloatType) = () patternMatch (Subtract IntType) = () patternMatch (Subtract FloatType) = () Should be an exhaustive pattern match. One way of doing this is to introduce separate datatypes for each operation, where it only has the allowed subtypes: newtype StringType