在 GHCi 中定义函数签名
Defining function signature in GHCi
在 Haskell 的解释器 GHCi 中定义函数签名不起作用。从 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
)?
您可以在ghc
交互式shell中定义函数签名。然而,问题是您需要在单个命令中定义函数。
您可以使用 分号 (;
) 分隔两部分:
Prelude> <b>square :: Int -> Int;</b> square x = x * x
请注意,这同样适用于具有多个子句的函数。如果你写:
Prelude> is_empty [] = True
Prelude> is_empty (_:_) = False
您实际上用第二条语句覆盖了前面的is_empty
函数。如果我们随后使用空列表进行查询,我们将得到:
Prelude> is_empty []
*** Exception: <interactive>:4:1-22: Non-exhaustive patterns in function is_empty
所以ghci
将最后一个定义作为单子句函数定义。
同样你必须这样写:
Prelude> is_empty[] = True<b>;</b> is_empty (_:_) = False
多行输入需要在:{
和:}
命令中换行。
λ> :{
> square :: Int -> Int
> square x = x * x
> :}
square :: Int -> Int
这里有三种方法:
>>> square :: Int -> Int; square = (^2)
>>> let square :: Int -> Int
... square = (^2)
...
>>> :{
... square :: Int -> Int
... square = (^2)
... :}
第二个需要你:set +m
;我将其包含在我的 ~/.ghci
中,以便它始终处于打开状态。
在 Haskell 的解释器 GHCi 中定义函数签名不起作用。从 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
)?
您可以在ghc
交互式shell中定义函数签名。然而,问题是您需要在单个命令中定义函数。
您可以使用 分号 (;
) 分隔两部分:
Prelude> <b>square :: Int -> Int;</b> square x = x * x
请注意,这同样适用于具有多个子句的函数。如果你写:
Prelude> is_empty [] = True
Prelude> is_empty (_:_) = False
您实际上用第二条语句覆盖了前面的is_empty
函数。如果我们随后使用空列表进行查询,我们将得到:
Prelude> is_empty []
*** Exception: <interactive>:4:1-22: Non-exhaustive patterns in function is_empty
所以ghci
将最后一个定义作为单子句函数定义。
同样你必须这样写:
Prelude> is_empty[] = True<b>;</b> is_empty (_:_) = False
多行输入需要在:{
和:}
命令中换行。
λ> :{
> square :: Int -> Int
> square x = x * x
> :}
square :: Int -> Int
这里有三种方法:
>>> square :: Int -> Int; square = (^2)
>>> let square :: Int -> Int
... square = (^2)
...
>>> :{
... square :: Int -> Int
... square = (^2)
... :}
第二个需要你:set +m
;我将其包含在我的 ~/.ghci
中,以便它始终处于打开状态。