【问题标题】:How to declare inputs of a curried function as real in sml?如何在 sml 中将柯里化函数的输入声明为实数?
【发布时间】:2020-06-07 03:01:23
【问题描述】:

这是我想要输出为真实的咖喱阶乘函数的代码

fun pow(x:real) (n:real)= if (n=0.0) then 1.0 else x:real*pow(x:real) (n-1:real) ;

但是我的语法真的很错误,我该如何解决这个问题?

【问题讨论】:

  • 下面的问答:Why can't I compare reals in Standard ML?real 阶乘函数为例(虽然重写为模式匹配)。但我承认 ruakh 的real 解决方案在下面避免了比较也非常简洁。
  • 为什么不使用内置的Math.pow : real * real -> real呢?

标签: arguments sml currying smlnj ml


【解决方案1】:

我想你想要的是:

fun pow x n =
  if n = 0
  then 1.0
  else x * pow x (n - 1)

或者,如果您想更明确地了解类型:

fun pow (x : real) (n : int) : real =
  if n = 0
  then 1.0
  else x * pow x (n - 1)

即:

  • 我想你希望nint 类型,而不是real 类型。 (您的方法只有在 n 是非负整数时才有意义,否则递归将永远进行。)
  • 你不需要到处都有那么多:real-s;他们不添加任何东西,因为编译器可以推断类型。

【讨论】:

    猜你喜欢
    • 2013-10-04
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    相关资源
    最近更新 更多