将数据构造函数映射到类型

Sea*_*ess 4 haskell types algebraic-data-types

我正在创建一个允许管理员构建表单的应用程序,用户可以填写该表单.问题可以是不同类型的.每种问题都对应于一种响应数据.

是否可以在类型级别对此进行编码?你会如何组织这个?

data QuestionType = EmailText | PlainText | Numeric

-- this doesn't have any response information, it's the metadata
-- about the question itself.
data Question = { id :: ID, label :: Text, questionType :: QuestionType }

data Answer = { questionID :: ID, response :: Response }

-- I would like to map those question types to different response types
data Response = ???
-- EmailText => Text
-- PlainText => Text
-- Numeric   => Int
Run Code Online (Sandbox Code Playgroud)

我已经考虑过Type Families,除了我想要从不同的数据构造函数映射到不同的类型之外,它可以完美地工作,而类型族要为每个类型需要单独的类型.

这将非常适合单个ADT,响应信息包含在每个构造函数中,但我需要能够独立于响应处理问题类型.

我该怎么做呢?

chi*_*chi 8

我还没有完全理解你到底想要什么,但也许这可以作为一个起点:

{-# LANGUAGE DataKinds, GADTs #-}

data Response (qt :: QuestionType) where
  RPlainText :: Text -> Response PlainText
  REmailText :: Text -> Response EmailText
  RNumeric :: Int -> Response Numeric

data Answer qt = Answer {questionID :: ID, response :: Response qt}
Run Code Online (Sandbox Code Playgroud)

如果你不想要qt参数Answer qt,你可能需要存在类型来隐藏它,但是那时你可能想要以某种方式将它与问题联系起来.