Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count all elements in data class

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading