Defining a function signature in Haskell's interpreter GHCi doesn't work. Copying an example from this page:
Prelude> square :: Int -> Int
<interactive>:60:1: error:
• No instance for (Show (Int -> Int)) arising from a use of ‘print’
(maybe you haven't applied a function to enough arguments?)
• In a stmt of an interactive GHCi command: print it
Prelude> square x = x * x
How can I declare a function signature and then give function definition in Haskell interactively? also: why can't I simply evaluate the function and see its type (e.g. Prelude> square
) once it has been defined?
To better understand the error message, take a look at the types, in ghci you can use the `:t ` command which will show you the type for a given expression If instead declaring the types like in this example
Function Signature: When a Function is defined, a set of parameters is also defined within the parentheses to define the type of arguments it will be receiving on the function call. This function signature may hold one parameter or a list of parameters.
This can be achieved in two ways – We can get function Signature with the help of signature () Function. It takes callable as a parameter and returns the annotation. It raises a value Error if no signature is provided. If the Invalid type object is given then it throws a Type Error.
This function signature may hold one parameter or a list of parameters. A subroutine or Function whose signature is defined can receive arguments only of the type defined in the subroutine. It will generate an error if the arguments passed to the subroutine varies from its signature. A function signature tells a lot about the type of subroutine.
You can define a function signature in the ghc
interactive shell. The problem however is that you need to define functions in a single command.
You can use a semicolon (;
) to split between two parts:
Prelude> square :: Int -> Int; square x = x * x
Note that the same holds for a function with multiple clauses. If you write:
Prelude> is_empty [] = True
Prelude> is_empty (_:_) = False
You have actually overwritten the previous is_empty
function with the second statement. If we then query with an empty list, we get:
Prelude> is_empty []
*** Exception: <interactive>:4:1-22: Non-exhaustive patterns in function is_empty
So ghci
took the last definition as a single clause function definition.
Again you have to write it like:
Prelude> is_empty[] = True; is_empty (_:_) = False
Multi-line input needs to be wrapped in the :{
and :}
commands.
λ> :{
> square :: Int -> Int
> square x = x * x
> :}
square :: Int -> Int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With