【发布时间】:2019-11-09 22:22:20
【问题描述】:
我在 Haskell 中递归思考时遇到了问题。
我正在尝试构建一个调查应用程序,在该应用程序中,问题会根据用户的回答有条件地引发新问题。
我得到了:
- Questions - 问题列表
- QuestionPaths - 导致新问题的问题路径列表
- Answers 用户答案列表
您可以将QuestionPaths 视为一个元组列表,其中:
type QuestionPath = (QuestionId, AnswerChoice, NextQuestionId)
基本上会这样写:如果用户回答问题 QuestionId 有答案 AnswerChoice,问他 NextQuestionId 下一个。
我尝试使用multiway trees 对这个问题域建模(节点可以有多个子节点):
data YesNo = Yes | No
data AnswerChoice = Skip
| Boolean YesNo
| ChooseOne [Text]
type Condition = AnswerChoice
data QuestionTree = QuestionNode {
question :: Question
, condition :: Condition
, userAnswer :: Maybe AnswerChoice
, children :: QuestionForest
}
type QuestionForest = [QuestionTree]
不幸的是,我现在对如何编写构成这样的树的算法一无所知。
我基本上需要这些函数来组合和遍历:
-- Constructs the tree from seed data
constructTree :: Questions -> QuestionPaths -> Answers -> QuestionTree
-- | Inserts answer to question in the tree
answerQuestion :: Question -> AnswerChoice
-- | Fetches the next unanswered question by traversing the tree.
getNextUnanswered :: QuestionTree -> Question
能否请您帮助我了解构建和遍历此类树的最佳方法是什么?
【问题讨论】:
-
地图可能更合适:
type QuestionTree = Data.Map.Map (QuestionID, AnswerChoice) QuestionID. -
或
Map QuestionID (Map AnswerChoice QuestionID)用于“咖喱”版本。 -
@chepner 那将如何替换树?我的意思是树是要构建的结构,以便可以按顺序向用户询问一系列条件问题。比如“你去健身房了吗?”是 -> “你在健身房锻炼了多长时间?”
-
@Hopia 试试看。