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

Alia alia_khouri at yahoo.com
Mon Nov 21 14:46:28 CET 2011


I've retitled this post just in case (-:

Having spent some more time on the prior post (questionnaire data design patterns), I've managed
to produce a version that allows for heterogeneous lists but that seems to necessarily involve existential
quantification.

Three question remain:
(1) figure out how to show 'questions' in version3.hs (I'm stumped so far)
(2) figure out how to make Question and its subtypes polymorphic in the context of existential quantification:
    such that you can have a Choice a where a is an Int and another Choice Double, etc... yet still allow for
    heterogeneous lists so that questions = [open ...., test ...., choice ...] would still be possible.
(3) translate version3.hs to use records (if possible)

<version3.hs>

{-# LANGUAGE ExistentialQuantification #-} 
{-# LANGUAGE TypeSynonymInstances #-}

module Main where

import Text.Show.Functions

-- dummy funcs for now
class Question_ a where
    ask        :: a -> String
    view       :: a -> String
    parse      :: a -> String
    

data Question = forall a. Question_ a => Question a

type Name          = String
type QString       = String
type AnswerType    = String
type CorrectAnswer = String
type Option        = (String, String)
type Options       = [Option]

-- question types
data Open      = Open   Name QString AnswerType
data Test      = Test   Name QString AnswerType CorrectAnswer
data Choice    = Choice Name QString AnswerType CorrectAnswer Options

instance Question_ Open where
    ask   (Open n q a) = n
    view  (Open n q a) = q
    parse (Open n q a) = a

instance Question_ Test where
    ask   (Test n q a c) = n ++ c
    view  (Test n q a c) = q ++ c
    parse (Test n q a c) = a ++ c

instance Question_ Choice where
    ask   (Choice n q a c os) = n ++ c 
    view  (Choice n q a c os) = q ++ c
    parse (Choice n q a c os) = a ++ c

instance Question_ Question where
    ask   (Question q) = ask   q
    view  (Question q) = view  q
    parse (Question q) = parse q

--
-- Smart constructor
--

open :: Name -> QString -> AnswerType -> Question
open n q a = Question (Open n q a)

test :: Name -> QString -> AnswerType -> CorrectAnswer -> Question
test n q a c = Question (Test n q a c)

choice :: Name -> QString -> AnswerType -> CorrectAnswer -> Options -> Question
choice n q a c os = Question (Choice n q a c os)

questions :: [Question]
questions = [ open   "q1" "what is your name" "str"
            , test   "q2" "what is 1+1?"      "int" "2"
            , choice "q3" "what is 2+2?"      "int" "4" [("a", "4")]
            ]
</version.hs>

Alia



            ]




More information about the Beginners mailing list