Defining Function Signature in GHCi

Defining a function signature in a Haskell GHCi interpreter does not 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 a function definition in Haskell interactively? also: why can't I just evaluate the function and see its type (e.g. Prelude> square ) after it has been defined?

+5
source share
3 answers

You can define the function signature in the ghc interactive shell. However, the problem is that you need to define functions in one command .

You can use a semicolon ( ; ) to separate between two parts:

 Prelude> square :: Int -> Int; square x = x * x 

Note that the same is true for a function with multiple sentences . If you write:

 Prelude> is_empty [] = True Prelude> is_empty (_:_) = False 

Actually, the previous is_empty function is is_empty with the second statement. If we then request an empty list, we get:

 Prelude> is_empty [] *** Exception: <interactive>:4:1-22: Non-exhaustive patterns in function is_empty 

So ghci has adopted the latter definition as the definition of the function of a single sentence.

Again you need to write it like:

 Prelude> is_empty[] = True ; is_empty (_:_) = False 
+11
source

Multiline input must be wrapped in the commands :{ and :} .

 Ξ»> :{ > square :: Int -> Int > square x = x * x > :} square :: Int -> Int 
+8
source

Here are three ways:

 >>> square :: Int -> Int; square = (^2) >>> let square :: Int -> Int ... square = (^2) ... >>> :{ ... square :: Int -> Int ... square = (^2) ... :} 

The second requires you :set +m ; I include this in my ~/.ghci so it is always on.

+4
source

Source: https://habr.com/ru/post/1270299/


All Articles