gpt4 book ai didi

haskell - 没有因使用 ‘shouldBe’ 而产生的 (Show a0) 实例

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

我是 Haskell 新手,我正在努力学习 hspec同时。

module ExercisesSpec where

import Test.Hspec
import Test.QuickCheck
import Control.Exception (evaluate)


halve :: [a] -> ([a], [a])
halve xs = splitAt (length xs `div` 2) xs

main :: IO ()
main = hspec $ do
describe "halve" $ do
it "0 elements" $ do
halve [] `shouldBe` ([],[])

it "1 element" $ do
halve [1] `shouldBe` ([],[1])

it "2 elements" $ do
halve [1,2] `shouldBe` ([1],[2])

it "3 elements" $ do
halve [1,2,3] `shouldBe` ([1],[2,3])

it "4 elements" $ do
halve [1,2,3,4] `shouldBe` ([1,2],[3,4])

尽管其余测试通过,但 0 个元素的测试失败。

No instance for (Show a0) arising from a use of ‘shouldBe’
The type variable ‘a0’ is ambiguous
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 38 others
In a stmt of a 'do' block: halve [] `shouldBe` ([], [])
In the second argument of ‘($)’, namely
‘do { halve [] `shouldBe` ([], []) }’
In a stmt of a 'do' block:
it "0 elements" $ do { halve [] `shouldBe` ([], []) }

当我在 ghci 中尝试时,它工作正常。

*Exercises> halve []
([],[])

有人可以帮助我吗?

最佳答案

啊,为了回答我自己的问题,我发现我需要使类型更具体。如果我添加 halve :: [Int] -> ([Int], [Int]) 就可以了高于我的职能。

引用我在类(class)讨论室读到的好答案:

pbl64k

There's certainly no Show instance derivable for lists in general. What about lists of functions? The REPL infers a concrete type that does have a Show instance. But don't expect [a] in general to have one -- unless you make one yourself.

树鸮

pbl64k is sort of right and sort of wrong. There is a Show instance for [a] if there is a Show instance for a. It's automatically derived. The trouble here is that Haskell doesn't know which instance it is. [] may look like a single value, (and in the machine code, it probably is), but at the Haskell level it's a polymorphic constructor. It can take on any list type, so you have to do something to say which list type you mean it to have.

关于haskell - 没有因使用 ‘shouldBe’ 而产生的 (Show a0) 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26953859/

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