【问题标题】:The true meaning of Lucid's "Term" typeLucid“术语”类型的真正含义
【发布时间】:2019-11-03 22:56:09
【问题描述】:

我一直在玩 Haskell,尝试使用 Servant 和 Lucid 创建一个非常简单的网站。此刻我达到了“我的代码有效,我不知道为什么”的阶段。 我尝试创建引导按钮。根据文档,它应该定义为:

<button type="button" class="btn btn-primary">Primary</button>

于是我找到了 Lucid.Html5 文档:https://hackage.haskell.org/package/lucid-2.9.11/docs/Lucid-Html5.html 并制定了创建按钮的函数:

button_ :: Term arg result => arg -> result

花了一些时间尝试找出正确的语法后,我想出了这个:

-- correctly replicates the html pasted above
button_ [type_ "button", class_ "btn btn-primary"] "Primary"

通常我会称其为胜利并专注于其他任务,但这对我来说似乎是一件真正的魔法。

文档说“button_”是一个函数,它接受一个参数“arg”并返回一个泛型类型“result”的值。但是,在我的应用程序中,“button_”显然需要两个参数并返回“Html ()”。

-- f                       arg                     arg again ??
button_ [type_ "button", class_ "btn btn-primary"] "Primary"

它必须对“Term”类型类做一些事情,但我不知道如何理解它。有人可以帮我弄这个吗 ?我尝试将模块加载到 ghci 并使用 ":t" 检查类型,但这对我没有太大帮助。

【问题讨论】:

  • 不同的功能,但完全相同的魔法。
  • 很公平。对不起,不知道这个事实:-)。我会查看您发布的文章,然后将我的问题作为重复项关闭。

标签: html haskell bootstrap-4 haskell-lucid


【解决方案1】:

Term 类型类非常方便——我们不需要不同的term 函数来创建带有或不带有属性的元素——但可能有点难以理解。

button_的定义是

-- | @button@ element
button_ :: Term arg result => arg -> result
button_ = term "button"

termTerm 类型类的方法,类型为:

term :: Text -> arg -> result   

也就是说:你给它元素的名称,一些类型取决于特定实例的参数,它返回一些类型取决于特定实例的结果。但是有哪些实例可用?一共有三个:

Term Text Attribute
-- here, term :: Text -> Text -> Attribute

这是用于创建属性,而不是元素。

Applicative m => Term (HtmlT m a) (HtmlT m a)
-- here, term :: Text -> HtmlT m a -> HtmlT m a

这是用于创建没有属性的元素。我们作为参数传递给termarg 是一段代表孩子的html,我们得到另一段html 作为回报。

(Applicative m, f ~ HtmlT m a) => Term [Attribute] (f -> HtmlT m a)
-- here, term :: Text -> [Attribute] -> HtmlT m a -> HtmlT m a

这是最令人困惑的一个,也是您的代码中使用的那个。这里,argAttribute 值的列表。这很清楚。但是result 是函数的类型!传递属性后,我们剩下 another 函数 HtmlT m a -> HtmlT m a 允许我们提供按钮的内容(在您的情况下为“Primary”)。

f ~ HtmlT m a 是另一个与此答案无关的问题。它只是说f 等于HtmlT m a。那为什么不直接放呢?好吧,在某些情况下,它可以以理想的方式帮助drive type inference

【讨论】:

    猜你喜欢
    • 2014-09-09
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多