haskell - 为什么简单的 Haskell 函数会拒绝表示为比率的 Fractional 参数?

标签 haskell types operator-precedence implicit-typing

诚然,我是 Haskell 新手。为了探索惰性,我在 ghci 中创建了一个函数,它返回它的第二个参数:

Prelude> let latter x y = y
latter :: t -> t1 -> t1

我可以用 Char 类型的参数调用它, [Char] , Num , Floating , 和 Fractional (以小数表示):
Prelude> latter 'x' 'y'
'y'
it :: Char

Prelude> latter "foo" "bar"
"bar"
it :: [Char]

Prelude> latter 1 2
2
it :: Num t1 => t1

Prelude> latter pi pi
3.141592653589793
it :: Floating t1 => t1

Prelude> latter 0.5 0.7
0.7
it :: Fractional t1 => t1

为什么我在尝试应用 latter 时会收到一个可怕的错误(这是什么意思)到 Fractional以比率表示:
Prelude> 1/2
0.5
it :: Fractional a => a

Prelude> latter 1/2 1/2

<interactive>:62:1:
    Could not deduce (Num (a0 -> t1 -> t1))
      arising from the ambiguity check for ‘it’
    from the context (Num (a -> t1 -> t1),
                      Num a,
                      Fractional (t1 -> t1))
      bound by the inferred type for ‘it’:
                 (Num (a -> t1 -> t1), Num a, Fractional (t1 -> t1)) => t1 -> t1
      at <interactive>:62:1-14
    The type variable ‘a0’ is ambiguous
    When checking that ‘it’
      has the inferred type ‘forall t1 a.
                             (Num (a -> t1 -> t1), Num a, Fractional (t1 -> t1)) =>
                             t1 -> t1’
    Probable cause: the inferred type is ambiguous

最佳答案

Haskell 中的函数应用程序绑定(bind)比其他任何东西都更紧密。所以

latter 1/2 1/2

读作
((latter 1) / (2 1)) / 2

申请21不是一个热门的想法,因为latter接受两个参数,latter 1实际上是一个函数。将功能除以某物也不是一个好主意。您可以使用一些括号来解决所有这些问题:
latter (1/2) (1/2)

关于haskell - 为什么简单的 Haskell 函数会拒绝表示为比率的 Fractional 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258308/

相关文章:

Haskell 平台与自制软件

haskell - 必须手动打开量化的类型类证据?

go - 分配一个字符串类型的golang

python - 在 Python 中区分标量、列表和字典参数的最佳方法?

c - 运算符优先级问题

c - C 中的运算符优先级

Javascript: z = z || [] 在不使用 VAR 时抛出错误 - 为什么?

haskell - 长度索引链表的融合

haskell - 从免费的替代仿函数生成 optparse-applicative 解析器

ios - Swift Xcode 从闭包内的通用类型参数获取 <<error type>>