一元限制是什么?

一元限制是什么?

我很困惑Haskell编译器有时如何推断出不像我预期的那样多态的类型,例如在使用无点定义时。

问题似乎是“单形限制”,默认情况下,这是在较早版本的编译器上设置的。

考虑以下Haskell程序:

{-# LANGUAGE MonomorphismRestriction #-}import Data.List(sortBy)plus = (+)plus' x = (+ x)sort = sortBy compare

main = do
  print $ plus' 1.0 2.0
  print $ plus 1.0 2.0
  print $ sort [3, 1, 2]

如果我用ghc我没有获得任何错误,可执行文件的输出如下:

3.03.0[1,2,3]

如果我更改main尸体:

main = do
  print $ plus' 1.0 2.0
  print $ plus (1 :: Int) 2
  print $ sort [3, 1, 2]

我没有编译时错误,输出变成:

3.03[1,2,3]

如预期的那样。但是,如果我试图将其更改为:

main = do
  print $ plus' 1.0 2.0
  print $ plus (1 :: Int) 2
  print $ plus 1.0 2.0
  print $ sort [3, 1, 2]

我得到一个类型错误:

test.hs:13:16:
    No instance for (Fractional Int) arising from the literal ‘1.0’
    In the first argument of ‘plus’, namely ‘1.0’
    In the second argument of ‘($)’, namely ‘plus 1.0 2.0’
    In a stmt of a 'do' block: print $ plus 1.0 2.0


产生以下错误:

test.hs:14:17:
    No instance for (Num Char) arising from the literal ‘3’
    In the expression: 3
    In the first argument of ‘sort’, namely ‘[3, 1, 2]’
    In the second argument of ‘($)’, namely ‘sort [3, 1, 2]’
  • 为什么

    ghc

    突然觉得

    plus

    不是多态的,需要

    Int

    争吵?唯一提到

    Int

    应用程序

    plus

    如果定义显然是多态的,这又有什么关系呢?
  • 为什么

    ghc

    突然觉得

    sort

    需要

    Num Char

    举个例子?
编译时会出现以下错误:
TestMono.hs:10:15:
    No instance for (Ord a0) arising from a use of ‘compare’
    The type variable ‘a0’ is ambiguous
    Relevant bindings include
      sort :: [a0] -> [a0] (bound at TestMono.hs:10:1)
    Note: there are several potential instances:
      instance Integral a => Ord (GHC.Real.Ratio a)
        -- Defined in ‘GHC.Real’
      instance Ord () -- Defined in ‘GHC.Classes’
      instance (Ord a, Ord b) => Ord (a, b) -- Defined in ‘GHC.Classes’
      ...plus 23 others
    In the first argument of ‘sortBy’, namely ‘compare’
    In the expression: sortBy compare
    In an equation for ‘sort’: sort = sortBy compare
  • 为什么

    ghc

    能够使用多态类型

    Ord a => [a] -> [a]

    sort?

  • 为什么

    ghc

    治疗

    plus

    plus'

    不一样?

    plus

    应该具有多态类型

    Num a => a -> a -> a

    我看不出这和

    sort

    但只有

    sort

    引发错误。



慕标琳琳
浏览 485回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP