[Haskell-beginners] data design for a questionnaire (retitled + update)

Alia alia_khouri at yahoo.com
Mon Nov 21 15:04:36 CET 2011


As a followup, I just received a simpler and more elegant solution due to Lorenzo Bolla which involves wrapping
the question type in another type and achieves the objective nicely. I think this is much cleaner than
using existential types as per my prior posting.

<version4.hs>
module Main where

import Text.Show.Functions

-- type converters
str = id
int s = read s :: Int
float s = read s :: Double

data QuestionType = Open | Test | Choice deriving (Show, Eq)

data Question a = Question
    { questionName    :: String
    , questionText    :: String
    , questionType    :: QuestionType
    , answerFunc      :: (String -> a)
    , correctAnswer   :: Maybe a
    , options         :: Maybe [(String, a)]
    } deriving (Show)

data Question' = QuestionS (Question String) | QuestionI (Question Int) deriving (Show)

data QuestionSet a = QuestionSet
    { qsetTitle     :: String
    , qsetQuestions :: [Question']
    } deriving (Show)

data Questionnaire a = Questionnaire
    { questionnaireTitle        :: String
    , questionnaireQuestionSets :: [QuestionSet a]
    } deriving (Show)

q1 = Question
    { questionName  = "q1"
    , questionText  = "What is our name?"
    , questionType  = Open
    , answerFunc    = id
    , correctAnswer = Nothing
    , options       = Nothing
    }

q2 = Question
    { questionName  = "q2"
    , questionText  = "What is 1+1?"
    , questionType  = Test
    , answerFunc    = int
    , correctAnswer = Just 2
    , options       = Nothing
    }

q3 = Question
    { questionName  = "q2"
    , questionText  = "What is 2+1?"
    , questionType  = Choice
    , answerFunc    = int
    , correctAnswer = Just 3
    , options       = Just [("a", 2), ("b", 3), ("c", 4)]
    }

qset = QuestionSet
    { qsetTitle     = "simple questions"
    , qsetQuestions = [QuestionS q1, QuestionI q2, QuestionI q3]
    }

questionnaire = Questionnaire
    { questionnaireTitle        = "a questionnaire"
    , questionnaireQuestionSets = [qset]
    }


</version4.hs>


Alia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20111121/ada169c5/attachment.htm>


More information about the Beginners mailing list