在GHCi中定义功能签名 [英] Defining function signature in GHCi
问题描述
在Haskell的解释器GHCi中定义功能签名不起作用.复制此页面中的示例:
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
我如何声明一个函数签名,然后在Haskell中交互地给出函数定义?还:为什么我不能简单地对函数进行求值并在定义后查看其类型(例如Prelude> square
)?
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?
推荐答案
您可以在ghc
交互式外壳中定义函数签名.但是,问题在于您需要在单个命令中定义功能.
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
您实际上已经用第二条语句覆盖了先前的is_empty
函数.如果然后使用空列表进行查询,则会得到:
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
所以ghci
将最后一个定义作为单子句函数定义.
So ghci
took the last definition as a single clause function definition.
同样,您必须这样写:
Prelude> is_empty[] = True; is_empty (_:_) = False
这篇关于在GHCi中定义功能签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!