自定义高阶函数调用在约束错误中给出非类型变量参数

custom higher order function invocation gives Non type-variable argument in the constraint error

我是 Haskell 的新手,我试图找出高阶函数的基础。所以我创建了这个例子

times3 x = x * 3
fn f x = f (x+3)
transform x = x+5
mapThenComputeV1 f f1 x = f (f1 (transform (x)))

调用

mapThenComputeV1 fn times3 4

我遇到了这个异常

*Main> mapThenComputeV1 fn times3 4

<interactive>:2:1: error:
    * Non type-variable argument in the constraint: Num (t1 -> t2)
      (Use FlexibleContexts to permit this)
    * When checking the inferred type
        it :: forall t1 t2. (Num t1, Num (t1 -> t2)) => t1 -> t2

我完全没有头绪,请帮助我理解我做错了什么。

您的 mapThenComputeV1 类型为 (a -> b) -> (Int -> a) -> Int -> b(或类似的类型)。

您尝试将其应用于 fn times3 4

fn :: (Int -> a) -> Int -> a

所以 haskell 尝试将 mapThenComputeV1 应用于 fn,但发现类型不匹配。 Int 无法推断为 (Int -> a)

PS:尝试将显式类型添加到您的定义中。它通常可以帮助我发现问题。

PPS:如果你解释你想用 mapThenComputeV1 实现什么,我们可以帮助你修正你的例子。

mapThenComputeV1 中的参数 f 是您要应用的函数。您传递的 fn 接受两个参数,但 mapThenComputeV1 正文中有额外的括号。 试试这个:

mapThenComputeV1 f f1 x = f f1 (transform (x))
output> 36

但我不确定这是否是您期望达到的。