我可以有一个名为"/"的值构造函数吗? [英] Can I have a value constructor named "/""?
问题描述
我已经声明了具有以下结构的递归数据类型:
I've declared a recursive data type with the following structure:
data Path = GET | POST | Slash Path String
我真的很想将最后一个值构造函数重命名为/
,这样我就可以在诸如GET /"controller"/"action"
之类的可爱表达式中插入它.但是,如果我尝试这样做:
I'd really like to rename that last value constructor to /
so that I can infix it in cute expressions like GET /"controller"/"action"
. However, if I try to do so:
import Prelude hiding ((/))
infixr 5 /
data Path = GET | POST | Path / String
...然后我得到了:
...then I get this:
Path.hs:4:30: parse error on input `/'
如果我将/
替换为:/
或其他任何以:
开头的特殊字符序列,那么同样的三行编译也很好.
Those same three lines compile just fine if I replace /
with :/
or any other special character sequence beginning with :
.
那么,有什么方法可以命名我的值构造函数/
?我知道我可以将其命名为Slash
,然后声明一个单独的函数:
So, is there any way I can name my value constructor /
? I know that I can just name it Slash
and then declare a separate function:
(/) :: Path -> String -> Path
(/) = Slash
...但是那样不会让我进行模式匹配,如下所示:
...but that won't let me pattern match, as in:
request :: Path -> String
request path = case path of GET /"hello" -> "Hello!"
GET /"goodbye" -> "Goodbye!"
推荐答案
简短答案:否.
长答案:类型类,类型名称和数据构造函数必须以大写字母或冒号开头(其中某些要求使用语言扩展名).其他所有内容都必须以小写字母或任何其他允许的符号开头.
Long answer: Type classes, type names, and data constructors must begin with either a capital letter or a colon (some of this requires using a language extension). Everything else must begin with a lowercase letter or any other allowed symbol.
请注意,通常是小写字母标识符的变量类型遵循相同的规则,并且不以冒号开头.
Note that type variables, which are normally lowercase identifiers, follow the same rules and do not begin with a colon.
另请参见 GHC用户指南,用于启用类型运算符.我认为,始终允许使用数据构造函数.
See also the GHC user's guide for enabling type operators. Data constructors are always allowed, I think.
就您而言,我个人将使用(:/)
.看起来还不错,过了一会儿您就习惯了忽略冒号.有些人也喜欢尾随冒号,特别是如果数据在某种意义上是对称的".
Personally, in your case I'd just use (:/)
. It doesn't look that bad, and after a while you get used to ignoring the colons. Some people like a trailing colon as well, especially if the data is "symmetric" in some sense.
这篇关于我可以有一个名为"/"的值构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!