Union type list

387 views
Skip to first unread message

John Orford

unread,
May 20, 2016, 1:41:38 PM5/20/16
to elm-discuss
Why isn't something like

List (A | B)

possible?

Zinggi

unread,
May 20, 2016, 1:52:26 PM5/20/16
to Elm Discuss
It is, you just have to create a type for your union type.
e.g.
type Union a b = A a | B b
then you can use e.g.
list : List (Union Int String)
list = [A 1, B "bla"]

Is that what you wanted?

John Orford

unread,
May 20, 2016, 2:11:47 PM5/20/16
to Elm Discuss

Yup.  Thanks!


--
You received this message because you are subscribed to the Google Groups "Elm Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Zinggi

unread,
May 20, 2016, 2:27:40 PM5/20/16
to Elm Discuss
No problem.
You probably also want to read the documentation on types, specifically the section about union types.

Joey Eremondi

unread,
May 20, 2016, 2:46:49 PM5/20/16
to elm-d...@googlegroups.com
The key to remember here is that Elm doesn't have what are traditionally called union types, we have "Tagged union types". There's never a time when you can have As and Bs in a list, and not know if you have an A or a B. Every value in the list will be tagged with some constructor from what ever "type" declaration you use for your union.

Mark Hamburg

unread,
May 20, 2016, 6:15:30 PM5/20/16
to Elm Discuss
Elm also doesn't have generalized union types even with tags. For example, one can't have a universal NoOp message type that can be included in other message type definitions and recognized and generated from generic code.

Mark

Leroy Campbell

unread,
May 22, 2016, 4:59:26 PM5/22/16
to Elm Discuss
I assume if it were possible to have lists with mixed types, you'd lose some algebraic guarantees. How would you use such a list? There's probably another way to accomplish the same thing while retaining type safety.

Mark Hamburg

unread,
May 24, 2016, 12:12:38 PM5/24/16
to elm-d...@googlegroups.com
Whenever you accessed the list, you would get an element of type A | B. To use if further, you would need to type case it, pass it to something that wanted A| B or A | B | C etc, or put it through some sort of type cast operator that could give you a Maybe A or a Maybe B. Elm, of course, doesn't do any of those things, so this note is just to say that one could design a language that did. The "win" in this case would be to make it easier to create composite types — e.g., a value, an error, or nothing which isn't really quite the same in usage as either a Maybe (Result e t) or a Result e (Maybe t).

Mark
--
Reply all
Reply to author
Forward
0 new messages