为什么 ByteString 没有自动转换为 FilePath?

Why isn't ByteString converted automatically to FilePath?

我正在将(严格的)ByteString 传递给期望 System.IO.FilePath 的对象,它被声明为 type FilePath = String。我也在使用 {-# LANGUAGE OverloadedStrings #-}。我在某些地方进行了自动转换,但在这里却没有。我做错了什么?

Main.hs:33:40: error:
    • Couldn't match type ‘ByteString’ with ‘[Char]’
      Expected type: FilePath
        Actual type: ByteString

IIRC,OverloadedStrings 扩展不支持不同类型数据之间的神奇转换。它的作用是,当您编写 "foo" 这样的字符串文字时,编译器不仅可以将该文字视为 String,还可以将其视为 ByteString.

您可能需要 unpack 之类的东西才能将 ByteString 转换为 String

{-# LANGUAGE OverloadedStrings #-} 用法仅适用于 字符串文字 ,如 "a string"。在这种情况下,Haskell 隐式地在每个字符串文字前放置一个 fromString,因此它将字符串 literal 重写为 "a string"fromString "a string" .这只发生在 literals.

在Haskell中,据我所知,没有隐式转换。例如 IntFloat 之间的转换都是显式的。

另外请注意,IsString 类型类只有一个函数 fromString :: String -> a。所以这意味着它只适用于从字符串到那个实例(这里 ByteString),而不是相反。

您可以使用 unpack :: ByteString -> StringByteString 转换为 String