gpt4 book ai didi

haskell - 如何在 Haskell 中打印任何内容

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

我正在尝试编写一个返回列表中第一项的 Haskell 函数。

h [] = Nothing
h (x:xs) = x

当我用一个空列表调用它时:
main = print (h [])

我收到以下错误:
prog.hs:4:8:
No instance for (Show a0) arising from a use of `print'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Show Double -- Defined in `GHC.Float'
instance Show Float -- Defined in `GHC.Float'
instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
-- Defined in `GHC.Real'
...plus 23 others
In the expression: print (h [])
In an equation for `main': main = print (h [])

当我为函数提供空列表时,我希望结果为 Nothing。

最佳答案

这里有几个问题,我们先来添加一个合理的类型签名

h :: [a] -> Maybe a
h [] = Nothing
h (x:xs) = x

现在我们得到一个错误,我们返回一个普通的 x所以 x需要类型为 Maybe a .我们可能不想要这个,所以我们将它包装在 Just 中。构造函数
h (x:_) = Just x

现在解决你的问题。

请注意,这不是特定于您的功能,结果
main = print $ head []
main = print $ id []
main = print $ tail []

都是一样的。
[]的类型是 [a] .由于我们没有指定什么 a h []的类型是 Show a => Maybe a .额外的 Show进来是因为我们想打印我们的结果。但我们实际上并没有说什么 a所以 GHC 害怕无法默认它。

有两种方法可以修复它,愚蠢的方法是制作 h单态(monomorphisize?)到 h
h :: [Int] -> Maybe Int -- Bad

更聪明的方法是在我们的调用站点简单地选择一个具体类型。
main = print $ h ([] :: [Int])

我选择了 Int没有特别的原因,这并不重要。现在 Maybe Int是可打印的,所以我们都准备好了。 ::语法与顶级组件的工作方式相同,只是声明了 [] 的类型在我们的表达式中是 [Int] .

有趣的事实是,GHCi 的违约行为比 GHC 更激进。这意味着
 main = print []

在 GHCi 中是合法的,但在 GHC 中不合法。如果您遇到有趣的行为,请询问表达式的类型以查看默认值是什么
 :t []

关于haskell - 如何在 Haskell 中打印任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18858560/

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