Ell*_*tus 5 haskell types operator-precedence implicit-typing
我当然是Haskell的新手.为了探索懒惰,我在ghci中创建了一个返回其第二个参数的函数:
Prelude> let latter x y = y
latter :: t -> t1 -> t1
Run Code Online (Sandbox Code Playgroud)
我能够用的类型参数来调用它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
Run Code Online (Sandbox Code Playgroud)
为什么我得到了一个可怕的错误(什么意思)当我尝试应用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
Run Code Online (Sandbox Code Playgroud)
dfe*_*uer 17
Haskell中的函数应用程序比其他任何东西都紧密绑定.所以
latter 1/2 1/2
Run Code Online (Sandbox Code Playgroud)
被读为
((latter 1) / (2 1)) / 2
Run Code Online (Sandbox Code Playgroud)
应用2到1不是这么热的想法,因为latter需要两个参数,latter 1实际上是一个功能.用某种东西划分功能也不是一个好主意.您可以使用一些括号来解决所有这些问题:
latter (1/2) (1/2)
Run Code Online (Sandbox Code Playgroud)