需要统计组件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 :: Component -> Int
countButtons (TextBox []) = 0
countButtons (Container _ Button) = 1 + countButtons Container
Run Code Online (Sandbox Code Playgroud)
aComponent可以有三个值。如果用countButtons文字描述的话就是:
如果我的组件是 a TextBox,它将有 0 个按钮;如果它是 a Button,它将恰好有 1 个,如果它是 a ,Container它将具有与其子级一样多的按钮
在这种情况下,它几乎可以逐字翻译成 Haskell
countButtons :: Component -> Int
countButtons (TextBox _ _) = 0
countButtons (Button _ _) = 1
countButtons (Container _ child) = sum (fmap countButtons child)
-- |- this transform children into integers, and sum them all.
Run Code Online (Sandbox Code Playgroud)