在 ML 中使用列表头作为 int

Using list head as int in ML

我需要在 ML 中创建一个函数,其中参数是一个列表和一个 int,该函数获取列表中的每个元素并通过指定的 int 为它赋能。所以我已经编写了以下代码:

(* power function (power x y => x^y) *)
fun power x 0 = 1
| power x 1 = x
| power x y = x * (power x (y - 1));

这是主要功能:

fun powlist [] n = []
| powlist lst n = ((power hd(lst) n) :: (powlist tl(lst) n));

我认为这是有道理的,但编译器 (moscow ML) 显示如下: error message

函数应用程序具有最强的绑定力,而且hd(lst)确实是hd lst,因此(power hd(lst) n)被编译器理解为(power hd lst n),这意味着函数hd 作为参数传递给 power 函数而不是列表 lst.

一种修改方法是重新排列一些括号:

fun powlist []  n = []
  | powlist lst n = (power (hd lst) n) :: (powlist (tl lst) n)

但这不是惯用的 SML 代码。稍微好一点的方法是使用模式匹配:

fun powlist []      n = []
  | powlist (h::tl) n = (power h n) :: (powlist tl n)

最好的方法可能是使用标准 List.map 函数,它更通用,在某些 SML 实现中实现为 tail-recursive

fun powlist lst n = List.map (fn x => power x n) lst

顺带一提,power函数可以写得更简洁一点:

fun power x 0 = 1
  | power x y = x * (power x (y - 1))