高阶函数在SML中完成作业

时间:2013-03-29 20:30:01

标签: sml ml higher-order-functions

我在编写一个函数列表函数和参数时遇到问题,然后使用传递的参数调用每个函数,返回调用结果列表。 示例:build [f, g, h] 2将返回此值,但调用的函数和结果而不是调用:[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>)

最后,我放弃并试图做一些研究。我发现了以下问题:Higher Order Functions in 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错误消息,但这对我来说太陌生了。

p.s。:函数不能通过build(函数,参数)调用,它需要是两个参数而不是2个参数的元组。

2 个答案:

答案 0 :(得分:0)

一个简单的解决方案是使用标准的高阶函数映射:

fun build functions arg = map (fn f => f arg) functions;

答案 1 :(得分:0)

stdIn:2.14-2.16 Error: infix operator "::" used without "op" in fun dec

以上错误是因为你没有在f :: rest之外使用过brato,所以这可以解决为

fun build [] argument = []
|   build (f::rest) argument = [f(argument)] @ build rest argument;

sml解释器无法理解这是列表...