Open theliuk opened 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 []) = []
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
In this caseElem ais a data constructor, right? But how does pattern matching work in general with user-defined data types?
Elem a
Regards,
Luca
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 case
Elem a
is a data constructor, right? But how does pattern matching work in general with user-defined data types?Regards,
Luca