如何摆脱$(...)和[| ... |]语法使用模板Haskell函数? [英] How to get rid of $(...) and [| ... |] syntax when using a Template Haskell function?

查看:126
本文介绍了如何摆脱$(...)和[| ... |]语法使用模板Haskell函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图学习一些模板哈斯克尔。作为练习,我编写了一个函数,可以生成 isLeft isRight (灵感来自这个问题)。这是我谦虚的尝试:

  isA connam = do 
ConE nam < - connam
nn< - newNamep
lamE [varP nn] $ caseE(varE nn)[
match(conP nam [wildP])(normalB [| True |])[],
匹配wildP (normalB [| False |])[]
]

问题是我有写 $(isA [| Left |]),而不是更直观的 isA Left 。是否有可能摆脱丑陋的语法?我似乎无法在文档中找到答案。



该函数仅适用于一个参数的构造函数,但这是针对另一个问题

解决方案

语法对于原因;通知读者这里有编译时间的魔法。您只能在拼接处于顶层时消除 $(...)



然而,我们可以消除 [|通过接收 Name 而不是 Exp

  isA nam = do 
nn < - newNamep$ b $ (normalB [| True |])[],
符合wildP(normalB [| False |])[bPlamE [varPnn] $ caseE(varEnn)[
match(conPnam [wildP] []
]

要使用它,您可以编写 $(isA'Left),这对眼睛来说更容易一些。



作为奖励,如果你尝试给它以外的东西一个名称,你会得到一个类型错误,而不是无可辩驳的模式匹配错误。 模板Haskell语法


I'm trying to learn some Template Haskell. As an exercise, I wrote a function that can generate things like isLeft and isRight (inspired by this question). Here's my humble attempt:

isA connam = do
    ConE nam <- connam
    nn <- newName "p"
    lamE [varP nn] $ caseE (varE nn) [
                       match (conP nam [wildP]) ( normalB [| True |] ) [],
                       match wildP ( normalB [| False |] ) [] 
                     ]

The problem is that I have to write $(isA [| Left |]) instead of the more intuitive isA Left. Is it possible to get rid of the ugly syntax? I can't seem to find the answer in the documentation.

The function only works with one-argument constructors, but this is for another question.

解决方案

The syntax is there for a reason; to inform the reader that there is compile-time magic going on here. You can only eliminate the $(...) when your splice is at the top level.

However, we can eliminate the [| ... |] and also make the code more type-safe by taking in a Name instead of an Exp:

isA nam = do
    nn <- newName "p"
    lamE [varP nn] $ caseE (varE nn) [
                       match (conP nam [wildP]) ( normalB [| True |] ) [],
                       match wildP ( normalB [| False |] ) [] 
                     ]

To use this, you'd write $(isA 'Left), which is a little easier on the eyes.

As a bonus, if you try giving it something other than a Name, you get a type error instead of an irrefutable pattern match error.

See also: Template Haskell Syntax

这篇关于如何摆脱$(...)和[| ... |]语法使用模板Haskell函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆