[英]How to define the function's type signature?
doWithFunctionArg :: ? -> Int -> Int -> Int
doWithFunctionArg f a b = f a b
multiply :: Int -> Int -> Int
multiply a b = a * b
main = do
print $ doWithFunctionArg mutiple 7 8
我不確定函數的類型簽名是什么。 multiply :: Int -> Int -> Int
是乘法函數的函數類型簽名嗎? 如果是,如何為函數doWithFunctionArg
編寫類型簽名? doWithFunctionArg
函數具有三個參數,“ f”是函數類型,“ a”和“ b”是Int
,結果應該是Int
。 如果我是正確的,我應該用“?”寫什么?
multiply
的類型為doWithFunctionArg
Int -> Int -> Int
doWithFunctionArg
Int -> Int -> Int
,所以doWithFunctionArg
的類型為
-- typeof(multiply) -> Int -> Int -> Int
(Int -> Int -> Int) -> Int -> Int -> Int
實際上,您可以致電ghci尋求幫助:
Prelude> doWithFunctionArg f a b = f a b
Prelude> :t doWithFunctionArg
doWithFunctionArg :: (t2 -> t1 -> t) -> t2 -> t1 -> t
正如上面的delta所指出的,您可以省略類型簽名,然后要求GHC進行推斷。
您還可以將類型簽名保留在原處,僅替換未知的?
類型為通配符_
。 當GHC在類型中與_
相遇時,它將嘗試在其余類型簽名的上下文中僅推斷出該錯誤,從而導致推斷出的類型出錯。
這是GHCi演示:
> doWithFunctionArg :: _ -> Int -> Int -> Int ; doWithFunctionArg f a b = f a b
<interactive>:7:22: error:
• Found type wildcard ‘_’ standing for ‘Int -> Int -> Int’
To use the inferred type, enable PartialTypeSignatures
• In the type signature:
doWithFunctionArg :: _ -> Int -> Int -> Int
• Relevant bindings include
doWithFunctionArg :: (Int -> Int -> Int) -> Int -> Int -> Int
(bound at <interactive>:7:47)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.