[Haskell-beginners] Map on Nested Lists

Felipe Lessa felipe.lessa at gmail.com
Thu Apr 8 13:36:53 EDT 2010


On Thu, Apr 8, 2010 at 12:58 PM, Tim Sears <tim at timsears.com> wrote:
> If you don't mind choosing a different data type (always a good question to
> ask yourself in haskell) you could simply use your own nested lists....
> data Nested a  = One a | Nest [Nested a]
>                  deriving Show

Or, if you don't want to allow different "nested-ness":

  data Nested a = One a | Nest (Nested [a])

Examples of data types:

  One a :: Nested a
  Nest (One [a,b,c]) :: Nested a
  Nest (Nest (One [[a,b],[c,d]])) :: Nested a

  fromList :: [a] -> Nested a
  fromList = Nest . One

  fromList2 :: [[a]] -> Nested a
  fromList2 = Nest . Nest . One

The functor instance:

  instance Functor Nested where
    fmap f (One a) = One (f a)
    fmap f (Nest xs) = Nest (fmap (fmap f) xs)

Not tested, use at your own risk ;).

Cheers,

-- 
Felipe.


More information about the Beginners mailing list