【问题标题】:SML: pattern with constants?SML:带常量的模式?
【发布时间】:2021-07-11 18:20:02
【问题描述】:

我正在尝试在 SML 中编写模式匹配函数,但出现此错误

Error: non-constructor applied to argument in pattern: -

我正在尝试做这样的事情:

fun illegal (c:char) i j n m =
    let
        fun legal (#"A") 0 j = true
           |legal (#"B") i 0 = true
           |legal (#"C") i n = true
           |legal (#"D") m j = true
           | legal c  i j     = false
     in
        if (legal c i j = false) then 0
        else i
     end

**I suspect that the problem is that my n,m are two constants that have been valued right before. Any help appreciated
(I searched online and here I added parentheses in my chars, and tried some other stuff but my error persisted)** 

【问题讨论】:

  • 我看到了两种可能性:错误是指其他内容,或者您​​的原始代码有一个拼写错误,在您发布时已修复。

标签: sml smlnj


【解决方案1】:

当您进行模式匹配时,i 之类的东西不会检查它是否与现有的 i 绑定具有相同的值,而是引入了一个新的 i 绑定。

当你有:

legal (#"A") 0 j = true

你真正想要的是这样的:

legal (#"A") 0 j2 = j = j2

【讨论】:

  • 我想我用我的代码说的是“如果你得到 char “A”,然后是 0,然后是任何数字“然后返回 true ..”,你是说 ML 试图解决它j 的方程?我有点困惑
  • 啊。我的印象是您正在寻找#"A"0,然后是与提供给illegali 相同的值。当模式匹配您不会使用的值时,您可能会发现使用_ 很有帮助。所以fun legal (#"A") 0 j = true 变成了fun legal #"A" 0 _ = true多余的括号是不必要的。
猜你喜欢
  • 2012-06-23
  • 2015-01-18
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
  • 2015-07-24
相关资源
最近更新 更多