Syntax rules for Haskell infix datatype constructors
Asked Answered
I

1

9

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.

Imeldaimelida answered 18/11, 2014 at 17:11 Comment(3)
Off-topic, but: Dictionary t will be nothing like "a Python dictionary, a Ruby hashmap", etc. It's just a linked list, nothing more.Wynn
I disagree. My plan is to make multiple functions as well as monoid and functor instances to allow me to search for certain results with possible failings, without overusing Maybe. That's the easy part, but this I didn't understand.Imeldaimelida
What @Wynn is driving at are the following differences: you can't (directly) store a String and an Int in the same Dictionary, lookup is going to be worst-case linear time, you can't destructively update (and you're never going to get the nice dict[key] syntax). So it's not really like the datastructures you mention...Partida
M
9

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

Malaysia answered 18/11, 2014 at 17:21 Comment(3)
Strictly, a type-level operator would be an operator appearing on the left of the = sign. That requires a LANGUAGE pragma.Merrie
@Merrie better?Malaysia
I like to think of : as the "uppercase" version of ., and as we know Haskell constructors must start with uppercase... ;-)Hamann

© 2022 - 2024 — McMap. All rights reserved.