gpt4 book ai didi

haskell - 在 GHCi 中定义函数签名

转载 作者:行者123 更新时间:2023-12-03 15:22:55 25 4
gpt4 key购买 nike

在 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 中定义函数签名交互式外壳。然而问题是你 需要在单个命令中定义函数 .

您可以使用分号 ( ; ) 在两个部分之间进行拆分:

Prelude> square :: Int -> Int; 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; is_empty (_:_) = False

关于haskell - 在 GHCi 中定义函数签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45362445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com