繁体   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

我不确定函数的类型签名是什么。 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.

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