标签: pattern-matching

如何从字符串中提取下面的模式?

我有一个字符串,如下所示.

{(firstName1,lastName1,College1,{(24,25)},{(Street,23)},City1,Country1)}
Run Code Online (Sandbox Code Playgroud)

我需要从上面提取细节/值并将它们添加到列表中.我的意思是:

 ["firstName1","lastName1","College1","24","25","Street","23","City1", "country1"]
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现上述目标?我尝试了下面的方法,但不知道如何将所有花括号和括号放入模式中.

private static String flattenPigBag(String pigdata) {
    String s = "";
    Pattern p = Pattern.compile("\\{(.*)}");
    Matcher m = p.matcher(pigdata);
    while (m.find()) {
        s = m.group(1);
        System.out.println("answer : " + s);
    }
    return s;
}
Run Code Online (Sandbox Code Playgroud)

java regex string matcher pattern-matching

3
推荐指数
1
解决办法
82
查看次数

如何通过模式匹配从Scala中的列表中删除重复项?

作为家庭作业,我必须编写一个函数,从列表中删除重复项.它应该是递归的并且具有模式匹配.我不允许使用head,tail,contains等列表函数.
对于排序列表,我提出了这个解决方案:

def remove(u:List[Int]):List[Int] = {
  u match { case Nil => u
  case hd::hd2::tl => if(hd == hd2) remove(hd2::tl) else hd :: remove(hd2::tl)
  case hd::tl => hd :: remove(tl)
  }
}
Run Code Online (Sandbox Code Playgroud)

如何处理未排序的列表?

recursion scala list pattern-matching

3
推荐指数
1
解决办法
589
查看次数

实例实现的模式匹配

我正在尝试实现数据类型的show方法.

data OptionList a b = EmptyOpt | OptionList { optListHead :: a, optListTail :: b } deriving (Read)

instance (Show a, Show b) => Show (OptionList a b) where
    show (OptionList a EmptyOpt) = "{" ++ (show a) ++"}"
    show (OptionList EmptyOpt b) = "{" ++ (show b) ++"}"
    show (OptionList a b) = "{"++ (show a) ++ ", " ++ (show b) ++"}"
    show EmptyOpt = ""
Run Code Online (Sandbox Code Playgroud)

我希望OptionList不显示逗号,如果其中一个a或b具有由EmptyOpt构造的值.但编译器显示以下错误:

OptionList.hs:11:28:
    Couldn't match expected type ‘b’ …
Run Code Online (Sandbox Code Playgroud)

haskell pattern-matching typeclass

3
推荐指数
1
解决办法
663
查看次数

是否有一种简单的方法来改变Rust中的枚举字段?

假设我们有一个看起来像这样的枚举:

enum MyEnum {
    Field1,
    Field2 {x: f64, y: f64},
    /* Maybe some other fields */
    MyString(String),
}
Run Code Online (Sandbox Code Playgroud)

现在我创建了这个子类型枚举的实例,MyString经过一些动作后我想改变它.例如:

fn main() {
    let mut my_enum = MyEnum::MyString("Hello, world".to_string());
    /* Some actions */
    // Mutating the string
    match my_enum {
        MyEnum::MyString(ref mut content) => {
            content.push('!');
        },
        _ => {}
    }
    // Printing the string
    match my_enum {
        MyEnum::MyString(content) => {
            println!("{}", content);
        },
        _ => {}
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,以这样的方式匹配是相当繁琐的,当我们正是从上下文知道my_enum可能是唯一的 MyString.我宁愿写这样的东西(不是正确的Rust语法):

my_enum@MyString.push('!');
println!("{}", my_enum@MyString);
Run Code Online (Sandbox Code Playgroud)

如果,假设 …

enums pattern-matching rust

3
推荐指数
2
解决办法
1585
查看次数

我可以在没有警告的情况下解压缩F#列表吗?

F#可以轻松解压元组.解包列表也是可行的,但编译器会发出警告:

let m = [1; 2; 3]
let [a; b; c] = m
// Incomplete pattern matches on this expression. For example, the value '[_;_;_;_]' may indicate a case not covered by the pattern(s)
Run Code Online (Sandbox Code Playgroud)

有没有办法避免这种警告?

f# list pattern-matching

3
推荐指数
1
解决办法
191
查看次数

Scala中的模式匹配和变量

我是Scala的新手,对模式匹配的工作原理有点疑惑.想象一下,我有以下几点:

case class Cls(i: Int)

case b @ Cls(i) => //Ok
case e : Cls => //Ok
case f @ Cls => //Ok
case s: Cls(i) =>  //compile error
case str: String => //ok
Run Code Online (Sandbox Code Playgroud)

我不太明白在哪里使用@以及在哪里使用:.是否有一些严格定义的规则?

scala pattern-matching

3
推荐指数
1
解决办法
320
查看次数

Haskell:用|来约束函数模式变量

当我浏览持久性源代码时,我在文件Quasi.hs中遇到了这个函数(我提到了一个标签,其相关代码等于master分支中当前状态的代码,因为标签的代码更不可能改变).在该行中takeConstraint ps tableName defs (n:rest) | not (T.null n) && isUpper (T.head n) = takeConstraint',参数模式后面有这个管道(|)字符.是的表达|和=类似的格局制约参数呢?那么我|在数学中将其解释为相同的符号,即"这样"吗?

takeConstraint :: PersistSettings
          -> Text
          -> [FieldDef]
          -> [Text]
          -> (Maybe FieldDef, Maybe CompositeDef, Maybe UniqueDef, Maybe UnboundForeignDef)
takeConstraint ps tableName defs (n:rest) | not (T.null n) && isUpper (T.head n) = takeConstraint' --- <<<<< This line
    where
      takeConstraint' 
            | n == "Unique"  = (Nothing, Nothing, Just $ takeUniq ps tableName defs rest, …
Run Code Online (Sandbox Code Playgroud)

haskell pattern-matching

3
推荐指数
1
解决办法
43
查看次数

在模式匹配中获取区分联合的案例标识符

如何->在模式匹配后获得推断类型?

例如:

type Type =
  | Complex1
  | Complex2
  | Number of int
  | Integer of int

let calculate = function
  | Number i -> Number (i + 1)
  | Integer i -> Integer (i + 1)
  | Complex1 | Complex2 as t -> t
Run Code Online (Sandbox Code Playgroud)

我想通过合并来缩短这个功能Number并Integer用或|图案.如何获取推断的案例标识符以使以下功能起作用:

let calculate' = function
  | Number i | Integer i ->
      // If this is Number, return Number (i + 1)
      // Else return Integer (i …
Run Code Online (Sandbox Code Playgroud)

.net f# ocaml functional-programming pattern-matching

3
推荐指数
1
解决办法
89
查看次数

记录模式匹配

根据这个被接受的答案,在F#和OCaml中,我需要使用下划线来丢弃记录的其余部分.但是,为什么handle'功能有效但handle功能不起作用?

type Type = Type of int

type Entity =
    { type' : Type
      foo : string }

let handle entities =
    match entities with
    | {type' = Type i; _ }::entites -> ()
    | [] -> ()

let handle' entities =
    match entities with
    | {type' = Type i }::entites -> ()
    | [] -> ()
Run Code Online (Sandbox Code Playgroud)

f# ocaml functional-programming record pattern-matching

3
推荐指数
1
解决办法
422
查看次数

python cv2错误地检测多个图像中的正方形

我在使用opencv检测正方形时遇到问题。

  1. 这是我在cv2.matchShapes中找到要匹配的形状的参考图像

带有正方形的参考图像

  1. 这是用于与参考图像进行比较的两个输入图像:

第一张图片:

带有五个正方形的相同正方形的参考图像

第二张图片:

参考图像,其中一个正方形内有五个正方形以及各种符号和字母

  1. 这是我使用的代码(对不起,格式较差):

    #!/usr/bin/env python
    # coding: utf-8
    
    import numpy as np
    import cv2
    import argparse
    import math
    
    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--image", required=True, help="path to input image")
    args = vars(ap.parse_args())
    
    img = cv2.imread(args["image"])
    # img = cv2.bitwise_not(img,img)
    # gray = cv2.imread(args["image"],0)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # gray = cv2.GaussianBlur(gray, (5, 5), 0)
    cv2.imshow('gray', gray)
    cv2.waitKey(0)
    
    ret, thresh = cv2.threshold(gray, 230, 255, 1)
    cv2.imshow('thresh', thresh)
    # cv2.imwrite('./wni230.png',thresh)
    cv2.waitKey(0)
    
    square_cnts = []
    
    ##################################################
    shape = cv2.imread('./shape1.png')
    shape_gray = …
    Run Code Online (Sandbox Code Playgroud)

python opencv image-processing pattern-matching

3
推荐指数
1
解决办法
782
查看次数