为什么 !-notation (bang-notation) 在 Idris REPL 中不起作用?

Why doesn't !-notation (bang-notation) work in Idris REPL?

我原以为它的计算结果是 3,但得到了一个错误:

Idris> :let x = Just 2
Idris> 1 + !x
(input):1:3-4:When checking an application of function Prelude.Interfaces.+:
        Type mismatch between
                Integer (Type of (_bindApp0))
        and
                Maybe b (Expected type)

我也在没有顶层绑定的情况下尝试了这个并且得到了

Idris> let y = Just 2 in !y + 1
Maybe b is not a numeric type

问题在于 !-notation 如何脱糖。

当你写 1 + !x 时,这基本上意味着 x >>= \x' => 1 + x'。而且这个表达式没有类型检查。

Idris> :let x = Just 2
Idris> x >>= \x' => 1 + x'
(input):1:16-17:When checking an application of function Prelude.Interfaces.+:
        Type mismatch between
                Integer (Type of x')
        and
                Maybe b (Expected type)

但这很有效:

Idris> x >>= \x' => pure (1 + x')
Just 3 : Maybe Integer

因此您应该添加 pure 以使事情正常进行:

Idris> pure (1 + !x)
Just 3 : Maybe Integer

Idris repl 中没有什么特别之处,这就是类型检查器的工作方式。这就是 Idris 教程中的 m_add 函数中有 pure 的原因:

m_add : Maybe Int -> Maybe Int -> Maybe Int
m_add x y = pure (!x + !y)