0
Prelude> -- I have 2 functions: f and g
Prelude> f x y = x + y
Prelude> g x = 2*x
Prelude> f 2 3
5

用 x=2 和 y=3表示$ f(x, g(y))*这很好用:

Prelude> f 2 (g 3)
8

为什么以下返回错误?

Prelude>
Prelude> f 2 g 3

<interactive>:19:1: error:
    • Non type-variable argument in the constraint: Num (a -> a)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall a. (Num a, Num (a -> a)) => a
Prelude> 
4

1 回答 1

4
f 2 g 3

是(因为函数应用程序left-associative):

f 2 g 3 = ((f 2) g) 3

这就是你得到这个错误的原因 - 它期望g有一个Num(因为它是andy中的参数)f x y = x+y+ :: Num a -> a -> a -> a

2因为文字可以是每个值,Num a但 GHC 不知道一个实例,因为Num它是一个函数a -> a

现在错误本身谈到了上下文 - 基本的 Haskell 不能有表单的约束Num ((->) a a)- 但你可以使用给定的扩展轻松(并且安全地)规避这个......然后你应该得到类型类的错误。

于 2021-05-22T16:25:05.920 回答