简体   繁体   中英

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? If yes, how can I write the type signature for the function doWithFunctionArg ? doWithFunctionArg function has three arguments, "f" is the function type, "a" and "b" are Int , the result should be the Int . If I'm right, what should I write in "?"

multiply is of type Int -> Int -> Int , so doWithFunctionArg is of type

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

Actually you can call ghci for help:

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.

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.

Here's a GHCi demo:

> 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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