riccardotommasini / ppl

This repository contains the material related to the practical classes of the course Principles of Programming Languages
Apache License 2.0
29 stars 12 forks source link

Pattern matching and data types #6

Open theliuk opened 6 years ago

theliuk commented 6 years ago

I'm trying to solve the 99 Haskell questions that you find at this link

I'm dealing with the following problem:

Flatten a nested list structure.

Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively).

It is said that a new data type is needed since Haskell's built-in lists are homogenous. This is the new data type:

data NestedList a = Elem a | List [NestedList a]

Then the function is defined as follows:

myFlatten :: (NestedList a) -> [a] myFlatten (Elem a ) = [a] myFlatten (List (x:xs)) = (myFlatten x) ++ (myFlatten (List xs)) myFlatten (List []) = []

I don't understand how pattern matching works in this case from the theoretical point of view. For example, if we consider

myFlatten (Elem a ) = [a]

In this caseElem ais a data constructor, right? But how does pattern matching work in general with user-defined data types?

Regards,

Luca