且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Haskell中缀数据类型构造函数的语法规则

更新时间:2022-10-17 10:31:40

以冒号开头的任何运算符都是类型构造函数或数据构造函数,但( - >)除外。如果你想要波浪号,你可以使用:〜> ,但是你不会使用不以冒号开头的东西。 来源


I'm trying to make a Haskell datatype a bit like a python dictionary, a ruby hash or a javascript object, in which a string is linked to a value, like so:

data Entry t = Entry String t
type Dictionary t = [Entry t]

The above code works fine. However, I would like a slightly nicer constructor, so I tried defining it like this:

data Entry t = String ~> t

This failed. I tried this:

data Entry t = [Char] ~> t

Again, it failed. I know that ~ has special meaning in Haskell, and GHCi still permits the operator ~>, but I still tried one other way:

data Entry t = [Char] & t

And yet another failure due to parse error. I find this confusing because, for some inexplicable reason, this works:

data Entry t = String :> t

Does this mean that there are certain rules for what characters may occur in infix type constructors, or is it a cast of misinterpretation. I'm not a newbie in Haskell, and I'm aware that it would be more idiomatic to use the first constructor, but this one's stumping me, and it seems to be an important part of Haskell that I'm missing.

Any operator that starts with a colon : is a type constructor or a data constructor, with the exception of (->). If you want the tilde, you could use :~>, but you're not going to get away with using something that doesn't start with a colon. Source