Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: How to use this data structure

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.

like image 448
Skyfe Avatar asked Oct 10 '13 17:10

Skyfe


People also ask

How do you use data types in Haskell?

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.

How do you define a type in Haskell?

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...

How are datatype in Haskell defined and created?

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.

How does show work in Haskell?

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.


1 Answers

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)
like image 193
bheklilr Avatar answered Nov 15 '22 05:11

bheklilr