2 ms·
> Regarding the type field, look for "enum EventType type;" in the article. OK. If I understand correctly, you want to use that field in other contexts than do
by tom_mellior 9y ago
> Regarding the type field, look for "enum EventType type;" in the article.
OK. If I understand correctly, you want to use that field in other contexts than doing a switch on it, whereas in Haskell the usual way of consuming the type tag is to do such a switch, as in the article's example:
case event of
ClickEvent x y -> <do click stuff>
PaintEvent color -> <do paint stuff>
// there are no other possible cases, so no default case needed
> For example, I could separate a large array of sum-type data into separate arrays, and also process them separately.
Sure, but you can do that with a case expression as above. Here is a complete example:
data Event = ClickEvent Int Int | PaintEvent Int
-- separate a list of Events into two lists, the first holding the payloads
-- of the click events, the other the payloads of the paint events
separate :: [Event] -> ([(Int, Int)], [Int])
separate [] = ([], [])
separate (event : events) =
case event of
ClickEvent x y -> ((x, y) : clicks, colors)
PaintEvent color -> (clicks, color : colors)
where
(clicks, colors) = separate events
example = [ClickEvent 1 2, PaintEvent 42, ClickEvent 3 4, PaintEvent 23]
Running it:
> separate example
([(1,2),(3,4)],[42,23])
You can now go ahead and process the list [(1,2),(3,4)] separately from [42,23].
(Depending on the exact specification and performance requirements, the code might be written a bit differently in the real world.)
EDIT: Ah, you edited your post while I was writing. Oh well. Regarding reifying constructors as integers or whatever, yes, you might have to write a two-line function to do that.
- jstimpfle 9y agoYep, sorry for the edit. I did the arrays example but then noticed it was not really an answer to your question, since it can be done with sum types in almost the same way.