如果“ {-# LANGUAGE OverloadedStrings #-} ”包含在源文件的顶部或 package.yaml 中(我使用的是堆栈),则
length "a" -- does not compile anymore.
Run Code Online (Sandbox Code Playgroud)
但是自定义功能length'工作正常
length' :: [a] -> Int
length' xs = sum [1 | _ <- xs]
Run Code Online (Sandbox Code Playgroud)
包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
Run Code Online (Sandbox Code Playgroud)
这是因为length有一个签名length :: Foldable f => f a -> Int,所以它可以是任何Foldable类型。如果您使用OverloadedStrings扩展名,则"foo"不再是 a String,它可以是任何类型IsString a => a,并且这些类型的多个也可以是Foldable f => f as 。
你可以做的是给编译器一个类型提示,例如:
length ("a" :: String)Run Code Online (Sandbox Code Playgroud)