idris - Prelude 如何允许 Nat 使用数字文字?

标签 idris syntactic-sugar

使用 Idris 进行类型驱动开发 ch。 4、他们说

The Prelude also defines functions and notation to allow Nat to be used like any other numeric type, so rather than writing S (S (S (S Z))), you can simply write 4.

Fin 也类似。它是如何实现这一目标的?我看过the source但我无法弄清楚。

最佳答案

从您链接通知的位置 fromIntegerNat :

||| Convert an Integer to a Nat, mapping negative numbers to 0
fromIntegerNat : Integer -> Nat
fromIntegerNat 0 = Z
fromIntegerNat n =
  if (n > 0) then
    S (fromIntegerNat (assert_smaller n (n - 1)))
  else
    Z

fromInteger在 Nat 的 Num 实现中:

Num Nat where
  (+) = plus
  (*) = mult

  fromInteger = fromIntegerNat

并转换整数 Nat

||| Casts negative `Integers` to 0.
Cast Integer Nat where
  cast = fromInteger

对于 Idris1,它将尝试通过那些“fromFunctions”从文字(例如 Char、String 或 Integer)转换为所需的任何类型(如上述来源之一的注释中所述:[...] '-5' 脱糖为 'negate (fromInteger 5)'),一般来说 Idris1 支持任意两种类型的隐式转换。 (http://docs.idris-lang.org/en/latest/tutorial/miscellany.html#implicit-conversions)

就 Idris2 而言,有一些 pragmas (%charLit fromChar, %stringLit fromString, %integerLit fromInteger) 提示编译器使用某些从文字到任何其他类型的转换函数.

关于idris - Prelude 如何允许 Nat 使用数字文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61603606/

相关文章:

python - 如果没有返回值,则不要调用函数

Python 断言——改进了失败的自省(introspection)?

vala - Idris:如何从 Vala/C 调用 Idris 函数并将字符串返回给 C/Vala

haskell - Idris 中依赖类型的限制

types - Idris 中是否存在宇宙不一致的重要示例?

layout - Haskell 记录语法

idris - 在 Idris 中定义组

idris - 如何在另一个 nixpkg 中使用与 nixpkg 一起安装的 idris 包?

python - 将循环打包到函数中以静音变量的Pythonic 方法?

c# - .NET Framework 支持空操作语法或单例