blaze-html, Haskell, toHtml 用法正确吗?

blaze-html, Haskell, correct toHtml usage?

有两件事我不明白: 1) 没有 {-# LANGUAGE OverloadedStrings #-} none 的典型代码,其中纯字符串作为属性的参数传递,有效;但是,只要有该指令,一切都很好。它在这种特殊情况下的作用是什么?在生产代码中使用它有多安全?

2) 以下一段代码:(toHtml $ "<script ... ></script>") 因我不太理解的内容而失败:

Ambiguous type variable ‘a0’ arising from the literal ... prevents the constraint ‘(Data.String.IsString a0)’ from being solved. Probable fix: use a type annotation to specify what ‘a0’ should be. These potential instances exist: instance Data.String.IsString H.AttributeValue -- Defined in ‘blaze-markup-0.8.2.1:Text.Blaze.Internal’ instance Data.String.IsString H.Tag -- Defined in ‘blaze-markup-0.8.2.1:Text.Blaze.Internal’ instance a ~ Char => Data.String.IsString [a] -- Defined in ‘Data.String’ ...plus 10 instances involving out-of-scope types

  1. 在标准 Haskell 中,像 "foo" 这样的字符串文字总是被解析为 String = [Char] 类型的值。 Blaze 在大多数地方不使用实际的 String 值,而是对每个语义不同的事物使用它自己的类型,如 AttributeValue。这意味着在没有 OverloadedStrings 的标准 Haskell 中,不可能将字符串文字传递给许多需要 AttributeValues、Tags 等的 Blaze 函数。当您设置-XOverloadedStrings,GHC 将允许字符串文字具有类型 Data.String.IsString p => p 而不是 String,因此您可以在具有 IsString 实例的某些类型的任何地方使用字符串文字预期的。这被所有 "standard" Blaze 代码使用。 OverloadedStrings 是一个相当简单的扩展——它基本上是为字符串文字做的,就像 Num 为整数文字做的一样——我不知道围绕它有任何大量的争议。我认为在生产代码中使用它应该是安全的,并且有几个生产代码库使用它。

  2. 此错误消息是由于 toHtml 在其第一个参数的类型上被普遍量化,但有一些限制:toHtml :: ToMarkup a => a -> Html 和---with OverloadedStrings---字符串的类型也是类型变量。基本上,GHC 知道将传递给 toHtml 的字符串文字的类型需要是某种类型,并且该类型需要具有 ToMarkupIsString 的实例,但是它没有任何方法可以确定该类型应该是什么!在这种情况下,看起来您可能正在寻找实际上在此处具有类型 String 的字符串文字,您可以通过手动注释文字获得该文字:toHtml ("foo" :: String),或使用 -XTypeApplications : toHtml @String "foo".