[英]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)显示以下内容: 错误消息
函数应用程序具有最强的绑定能力,而且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实现中作为尾递归实现:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.