[Haskell-beginners] data design for a questionnaire (retitled + update)
Alia
alia_khouri at yahoo.com
Thu Nov 24 10:32:47 CET 2011
Hi folks,
As the code (from my prior post) is not so relevant to the issue
at hand, it was quite reasonably suggested that I should simplify my
question somewhat. So here goes:
In my model, I have a Question record type, which has a type parameter
to take into account that answers can be evaluated to different types.
For example, I can ask a question which requires a Double as an
answer and another which requires an Int as an answer:
data Question a = Question {text:: String, answer:: Maybe a}
This question type is wrapped/boxed in another type to allow the
different questions to referenced in a list. Hence,
data Question' = QuestionS (Question String)
| QuestionI (Question Int)
| QuestionD (Question Double)
and I can now store the questions as follows:
questions = [ QuestionI {text="What's 1+1?", answer=Maybe 2}
, QuestionD {text="What's 1.0+1.5?", answer=Maybe 2.5}
]
Now to extract Question a from Question' I would have liked to write
the following:
extract :: Question' -> Question a
extract q = case q of
QuestionS x -> extractQString q
QuestionI x -> extractQInt q
QuestionD x -> extractQDouble q
but instead, I had to produce the following instead:
extractQString :: Question' -> Question String
extractQString (QuestionS q) = q
extractQInt :: Question' -> Question Int
extractQInt (QuestionI q) = q
extractQDouble :: Question' -> Question Double
extractQDouble (QuestionD q) = q
From what I understand so far, that specialized extraction or unboxing
functions are the way to go unless one uses language extensions like
GADTs which can be conceptually more complicated. Is this indeed the case,
or are there other ways to achieve generalized type unboxing while
remaining within the Haskell98 specification?
Best,
Alia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20111124/7878a9ff/attachment-0001.htm>
More information about the Beginners
mailing list