Why are polymorphic values not inferred in Haskell?

后端 未结 2 751
花落未央
花落未央 2020-11-27 06:25

Numeric literals have a polymorphic type:

*Main> :t 3
3 :: (Num t) => t

But if I bind a variable to such a literal, the polymorphism

2条回答
  •  醉梦人生
    2020-11-27 06:56

    It's the monomorphism restriction which says that all values, which are defined without parameters and don't have an explicit type annotation, should have a monomorphic type. This restriction can be disabled in ghc and ghci using -XNoMonomorphismRestriction.

    The reason for the restriction is that without this restriction long_calculation 42 would be evaluated twice, while most people would probably expect/want it to only be evaluated once:

    longCalculation :: Num a => a -> a
    longCalculation = ...
    
    x = longCalculation 42
    
    main = print $ x + x
    

提交回复
热议问题