21
我正在學習Haskell,當我遇到非常令人費解的事情時,我在ghci中玩耍。這個ghci會話中的類型是怎麼回事?
首先,創建一個簡單的附加功能:
Prelude> let add x y = x + y
注意,它與整型和浮點:
Prelude> add 3 4
7
Prelude> add 2.5 1.3
3.8
現在創建一個應用功能。它與$
(但不是中綴)相同。它像一個無操作上添加:
Prelude> let apply f x = f x
Prelude> apply add 3 4
7
Prelude> apply add 2.5 1.3
3.8
好了,現在讓add'
這是一樣的add'
但使用apply
:
Prelude> let add' = apply add
Prelude> add' 3 4
7
Prelude> add' 2.5 1.3
<interactive>:1:9:
No instance for (Fractional Integer)
arising from the literal `1.3' at <interactive>:1:9-11
Possible fix: add an instance declaration for (Fractional Integer)
In the second argument of `add'', namely `1.3'
In the expression: add' 2.5 1.3
In the definition of `it': it = add' 2.5 1.3
笏。
以下是類型:
Prelude> :t add
add :: (Num a) => a -> a -> a
Prelude> :t apply add
apply add :: (Num t) => t -> t -> t
Prelude> :t add'
add' :: Integer -> Integer -> Integer
Prelude>
爲什麼add'
有不同的類型apply add
?
這是ghci的古怪,或者這在Haskell中是真的嗎? (以及我怎樣才能說出不同?)
當我聽到「我在玩ghci並且看到一些奇怪的東西」時,我想「Monomorphism restriction」 – amindfv