Haskell组件中统计所有按钮数量的正确实现方法咨询
正确实现统计GUI组件中按钮数量的函数
先看定义好的Component数据类型与GUI实例:
data Component = TextBox {name :: String, text :: String} | Button {name :: String, value :: String} | Container {name :: String, children :: [Component]} gui :: Component gui = Container "My App" [ Container "Menu" [ Button "btn_new" "New", Button "btn_open" "Open", Button "btn_close" "Close" ], Container "Body" [TextBox "textbox_1" "Some text does here"], Container "Footer" []]
原countButtons函数存在模式匹配错误:
TextBox []不符合TextBox构造器的参数要求,TextBox需要两个String类型参数,而非空列表Container _ Button的模式错误,Container的第二个参数是组件列表,不是单个Button,递归调用的写法也不符合语法
正确实现需要递归遍历整个组件树,分三种情况处理:
- 遇到TextBox,返回0(不属于按钮)
- 遇到Button,返回1(计数加1)
- 遇到Container,递归统计每个子组件的按钮数,最后求和
最终正确的countButtons函数如下:
countButtons :: Component -> Int countButtons (TextBox _ _) = 0 countButtons (Button _ _) = 1 countButtons (Container _ children) = sum (map countButtons children)
调用countButtons gui会返回3,与GUI实例中的按钮数量一致。
内容的提问来源于stack exchange,提问作者NoOneCare
相关产品推荐
相关产品推荐

