Home > Software design >  Count all elements in data class
Count all elements in data class

Time:11-29

Need to count all buttons in component gui. Can't understand right way to work with this data object

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

CodePudding user response:

a Component can have three values. If you describe countButtons with words it wold be:

if my component is a TextBox, it would have 0 butons; If it is a Button, It would have exactly 1 and if it is a Container it would have as many buttons as its children has

In this case, It can be translated almost word by word into 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.
  • Related