使用预定义的复合函数在标准 ML 中编写幂函数

Writing power function in Standard ML with a predefined compound function

在标准 Ml 中编写幂函数时遇到问题。我正在尝试编写一个名为 exp 且类型为 int -> int -> int 的函数。

应用exp b e,对于非负e,应该returnb^e

例如exp 3 2应该return 9.exp必须用下面提供的函数compound来实现。 exp 不应该直接调用自己。这是 compound 函数,它接受一个值 n、一个函数和一个值 x。它所做的只是将函数应用于值 x n 次。

fun compound 0 f x = x 
  | compound n f x = compound (n-1) f (f x);

我无法弄清楚如何在没有递归的情况下编写这个函数,并且必须使用只能使用一个参数的函数的限制。任何人都知道从哪里开始?

这是我的:

fun exp b 0 = 1  
  | exp b e = (compound e (fn x => x*x) b)  

我知道这行不通,因为如果我输入 2^5,它会起作用: 2*2、4*4、16*16等

这可能不是 100% 正确的代码。我刚刚阅读了一些标准 ML 文档并获取了一些代码并为您的示例重新编写了它,但对于大多数编程语言来说,总体思路是相同的。

fun foo (num, power) =
let
  val counter = ref power
  val total = 1
in
  while !counter > 0 do (
    total := !total * num
    counter := !counter - 1
  )
end;

更清楚一些 pseudo-code:

input x, pow
total = 1
loop from 1 to pow
  total = total * x
end loop
return total

这不处理负指数,但它应该可以帮助您入门。

它基本上是一个关于指数真正含义的简单算法:重复乘法。

2^4 = 1*2*2*2*2 //The 1 is implicit
2^0 = 1

你们非常亲密。您对 exp 化合物 fn x => x*x 的定义(如您所见)不是您想要的,因为它反复对输入进行平方。相反,您想重复 乘以基数 。即fn x => b*x.

接下来,您可以根据 compound "does the right thing" 当被要求应用函数 0 次时实际删除 e = 0 的特殊情况。

fun exp b e = compound e (fn x => b*x) 1

我相信你可以这样做

  fun exp 0 0 = 1
  | exp b 0 = 1
  | exp b e = (compound (e - 1) (fn x => b * x ) b);