【问题标题】:Match if two values in an unorded list are the same如果无序列表中的两个值相同,则匹配
【发布时间】:2016-07-28 22:55:27
【问题描述】:

我有一个带有一些值(list 'foo 'bar 2 #t 42 9 2 'some) 的球拍列表。实际上,这些值遵循一些更具体的模式,但对于这个问题,这是无关紧要的。我想测试列表中是否有两个相同的值,在本例中为数字 2,并获取元素和其他元素。这是我的尝试:

#lang racket

(match (list 'foo 'bar 2 #t 42 9 2 'some)
  [(list-no-order a a rest ...)
     "Do some stuff"]
  [_ "Do some other stuff"])

模式是(list-no-order a a rest ...)。但是程序的解释失败了:

a11: unbound identifier;
 also, no #%top syntax transformer is bound in: a11

在我看来,转换宏时出现错误。如果将list-no-order 更改为list,则该模式有效,但当然前提是元素位于列表的开头。

我的模式是否错误,如果是,如何纠正它,或者预期的模式是不可能的,解决它的最佳方法是什么?

【问题讨论】:

  • 这是(match (list 2 2 #t) [(list-no-order asd asd dsa) "Do some stuff"])宏扩展后的结果:pastebin.com/K3PG44kY。我们可以看到有一个未绑定的 id asd8。也许宏有问题?
  • 报告于Github
  • 感谢您将此作为错误报告提交。 :)
  • 提交错误报告后,我发现该错误已在2009 中报告并重新提交by others。对于错误报告,一个名为 samth 的人负责分配 266 个未解决的错误。这些报告完全没有动静,我怀疑这种情况在未来几年会改变。当然,我可以尝试自己修复它,因为它是开源的,但我需要先学习复杂的 Racket 语法转换。相当令人失望。 :-(

标签: pattern-matching racket equality


【解决方案1】:

目前,最好的解决方法是使用#:when 条件:

#lang racket

(match (list 'foo 'bar 2 #t 42 9 2 'some)
  [(list-no-order a b rest ...)
   #:when (equal? a b)
   "Do some stuff"]
  [_ "Do some other stuff"])

【讨论】:

    【解决方案2】:

    我想知道您为什么要尝试模式匹配某些东西。通过您的问题和代码,我不清楚。我会通过纯列表处理来解决您的问题(至少据我所知)

    (filter
        (lambda (x)
            ;;filter for the first element of the prev created tuple and 
            ;;check if its larger than 1
            (> (first x) 1))
        (map
            (lambda (x)
                ;;tuple of the length of the prevously created group and the group itself
                (cons (length x) x))
            (group-by
                ;;just the element it seld
                (lambda (x)
                    x)
                (list 'foo 'bar 2 #t 42 9 2 'some))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      • 2020-05-18
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      相关资源
      最近更新 更多