函数长度 "a" 不编译,如果启用了重载字符串扩展



如果">{-#LANGUAGE OverloadedStrings#-}";包含在源文件的顶部,或package.yaml中(我使用的是堆栈(,然后是

length "a"  -- does not compile anymore.

然而,自定义功能length'在上运行良好

length' :: [a] -> Int 
length' xs = sum [1 | _ <- xs] 

Data.String是导入的-我认为问题是存在的,但是,我很想看看是否有人有类似的问题。

堆栈和GHC版本:2.3.1版,Git修订版x86_64 hpack-0.33.0,ghc-8.8.3

我使用的是mac-osx,但同样的错误也出现在Linux和windows中。

这是堆栈产生的错误:

/Users/admin1/Haskell/PROJECTS/orig1/src/Lib.hs:13:29: error:
• Ambiguous type variables ‘t0’,
‘a0’ arising from the literal ‘"a"’
prevents the constraint ‘(IsString (t0 a0))’ from being solved.
Probable fix: use a type annotation to specify what ‘t0’,
‘a0’ should be.
These potential instances exist:
instance (a ~ Char) => IsString [a] -- Defined in ‘Data.String’
...plus two instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the first argument of ‘length’, namely ‘"a"’
In the first argument of ‘show’, namely ‘(length "a")’
In the second argument of ‘($)’, namely ‘show (length "a")’
|
13 |     putStrLn $ show (length "a")  -- does not work, if "- OverloadedStrings" is on  

这是因为length有一个签名length :: Foldable f => f a -> Int,所以它可以是任何Foldable类型。如果使用OverloadedStrings扩展,则"foo"不再是String,它可以是任何类型的IsString a => a,其中的多个也可以是Foldable f => f as。

你可以做的是给编译器一个类型提示,例如:

length ("a":: String)

最新更新