令我感到困惑的是,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]
Run Code Online (Sandbox Code Playgroud)
如果我编译它,ghc我没有获得错误,可执行文件的输出是:
3.0
3.0
[1,2,3]
Run Code Online (Sandbox Code Playgroud)
如果我将main身体改为:
main = do
print $ plus' 1.0 2.0
print $ plus (1 :: Int) 2
print $ sort [3, 1, 2]
Run Code Online (Sandbox Code Playgroud)
我没有编译时错误,输出变为:
3.0
3
[1,2,3]
Run Code Online (Sandbox Code Playgroud)
正如所料.但是,如果我尝试将其更改为:
main = do
print $ …Run Code Online (Sandbox Code Playgroud) polymorphism haskell types type-inference monomorphism-restriction
在ghci,我可以这样做:
ghci> (fmap . const) 5 [1,2,3,4,5]
[5,5,5,5,5]
Run Code Online (Sandbox Code Playgroud)
但如果我尝试将子表达式提取(fmap . const)到变量中,我会收到错误:
ghci> let foo = (fmap . const)
<interactive>:3:12:
No instance for (Functor f0) arising from a use of `fmap'
The type variable `f0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Functor ((,) a) -- Defined in `GHC.Base'
instance Functor ((->) r) -- Defined in `GHC.Base'
instance Functor IO -- Defined in `GHC.Base'
...plus two …Run Code Online (Sandbox Code Playgroud) 看起来翻转对我的功能做了意想不到的事情
例1:
let m = flip max
:t max
max :: Ord a => a -> a ->
:t m
m :: () -> () -> ()
Run Code Online (Sandbox Code Playgroud)
例2:
let f x y = x + y
:t f
f :: Num a => a -> a -> a
let g = flip f
:t g
g :: Integer -> Integer -> Integer
Run Code Online (Sandbox Code Playgroud)
f可以评估浮点数,但g在看到浮点数时会抛出错误.但是当我跑步的时候
(flip f) 1.5 1.7
Run Code Online (Sandbox Code Playgroud)
评价很好!这些表达有什么区别?
我正在尝试编译简单的代码片段.
main = (putStrLn . show) (Right 3.423)
Run Code Online (Sandbox Code Playgroud)
编译导致以下错误:
No instance for (Show a0) arising from a use of `show'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Show Double -- Defined in `GHC.Float'
instance Show Float -- Defined in `GHC.Float'
instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
-- Defined in `GHC.Real'
...plus 42 others
In the second argument of `(.)', namely …Run Code Online (Sandbox Code Playgroud)