简体   繁体   English

如何定义函数的类型签名?

[英]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

I'm not sure what is the function's type signature. 我不确定函数的类型签名是什么。 multiply :: Int -> Int -> Int is the function's type signature for the multiply function right? multiply :: Int -> Int -> Int是乘法函数的函数类型签名吗? If yes, how can I write the type signature for the function doWithFunctionArg ? 如果是,如何为函数doWithFunctionArg编写类型签名? doWithFunctionArg function has three arguments, "f" is the function type, "a" and "b" are Int , the result should be the Int . doWithFunctionArg函数具有三个参数,“ f”是函数类型,“ a”和“ b”是Int ,结果应该是Int If I'm right, what should I write in "?" 如果我是正确的,我应该用“?”写什么?

multiply is of type Int -> Int -> Int , so doWithFunctionArg is of type multiply的类型为doWithFunctionArg Int -> Int -> Int doWithFunctionArg Int -> Int -> Int ,所以doWithFunctionArg的类型为

-- typeof(multiply) -> Int -> Int -> Int
(Int -> Int -> Int) -> Int -> Int -> Int

Actually you can call ghci for help: 实际上,您可以致电ghci寻求帮助:

Prelude> doWithFunctionArg f a b = f a b
Prelude> :t doWithFunctionArg
doWithFunctionArg :: (t2 -> t1 -> t) -> t2 -> t1 -> t

As delta points out above, you can omit the type signature and then ask GHC to infer it. 正如上面的delta所指出的,您可以省略类型签名,然后要求GHC进行推断。

You can also leave your type signature where it is, and only replace your unknown ? 您还可以将类型签名保留在原处,仅替换未知的? with a type wildcard _ . 类型为通配符_ When GHC meets with _ in a type, it will try to infer only that, in the context of the rest of the type signature, producing an error with the inferred type. 当GHC在类型中与_相遇时,它将尝试在其余类型签名的上下文中仅推断出该错误,从而导致推断出的类型出错。

Here's a GHCi demo: 这是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM