我在编写一个函数时遇到了麻烦,该函数将采用函数列表和参数,然后使用传递的参数调用每个函数,返回调用结果的列表。示例:build [f, g, h] 2
将返回 this,但使用调用的函数和结果而不是调用:[f(2), g(2), h(2)]
顺便说一下,使用 SML/NJ。
首先,我尝试了这种模式的许多变体:
fun build functions TheArgument = if functions = [] then [] else
[hd(functions) TheArgument] @ build tl(functions) TheArgument;
但它给出了以下错误:
stdIn:2.9-2.36 Error: operator is not a function [equality type required]
operator: ''Z
in expression:
(hd functions) TheArgument
stdIn:1.10-2.70 Error: case object and rules don't agree [tycon mismatch]
rule domain: ''Z list * 'Y
object: ('X list -> 'X list) * 'W
in expression:
(case (arg,arg)
of (functions,TheArgument) =>
if functions = nil then nil else (<exp> :: <exp>) @ <exp> <exp>)
最后,我放弃了,试着做一些研究。我发现了以下问题:SML/NJ 中的高阶函数
我尝试将其重新定义为:
fun build [] argument = []
| build f::rest argument = [f(argument)] @ build rest argument;
但随后编译器吐出这个:
stdIn:2.14-2.16 Error: infix operator "::" used without "op" in fun dec
stdIn:1.10-2.67 Error: clauses don't all have same number of patterns
stdIn:2.14-2.16 Error: data constructor :: used without argument in pattern
stdIn:1.10-2.67 Error: types of rules don't agree [tycon mismatch]
earlier rule(s): 'Z list * 'Y -> 'X list
this rule: ('W -> 'V) * 'U * 'T * 'W -> 'V list
in rule:
(f,_,rest,argument) => (f argument :: nil) @ (build rest) argument
我究竟做错了什么?
我在这里感到非常茫然,我可以处理神秘的 Java/C 错误消息,但这对我来说太陌生了。
ps:该函数不能通过 build(functions, argument) 调用,它需要是两个参数而不是 2 个参数的元组。