I have to work with a code for an assignment that includes the following data structure:
data Rose a = a :> [Rose a]
However, I have no idea how to work with this data structure, e.g.: how do I create an instance of it and how could I possibly loop through one?
If anyone could help me out on this.
In Haskell, you can have many constructors for your data type, separated by a vertical bar | . Each of your constructors then has its own list of data types! So different constructors of the same type can have different underlying data! We refer to a type with multiple constructors as a “sum” type.
One introduces, or declares, a type in Haskell via the data statement. In general a data declaration looks like: data [context =>] type tv1 ... tvi = con1 c1t1 c1t2...
Haskell has three basic ways to declare a new type: The data declaration, which defines new data types. The type declaration for type synonyms, that is, alternative names for existing types. The newtype declaration, which defines new data types equivalent to existing ones.
The shows functions return a function that prepends the output String to an existing String . This allows constant-time concatenation of results using function composition.
The constructor for this data type is (:>)
, and it's type is (:>) :: a -> [Rose a] -> Rose a
. You can construct values with it like
> 1 :> [] :: Rose [Int]
1 :> []
> 1 :> [2 :> [], 3 :> [1 :> []]] :: Rose [Int]
1 :> [2 :> [], 3 :> [1 :> []]]
It is functionally equivalent to
data Tree a = Node a [Tree a]
with different names, i.e. Tree <=> Rose
and Node <=> :>
If you wanted a Functor
instance for it, you'd do
instance Functor (Rose a) where
-- fmap :: (a -> b) -> Rose a -> Rose b
fmap f (a :> rest) = (f a) :> (map (fmap f) rest)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With