[Haskell-beginners] Re: [Haskell-cafe] lists of arbitrary depth

Richard O'Keefe ok at cs.otago.ac.nz
Tue Jul 13 19:20:07 EDT 2010


On Jul 13, 2010, at 9:00 PM, Christopher Done wrote:

> On 13 July 2010 10:58, vadali <shlomivaknin at gmail.com> wrote:\
>>
>> i want to define a function which takes as a parameter a list which  
>> can
>> contain other lists, eg. [1,[2,3],[4,[5,6]]]

What would the type of a list like that be?

What you _can_ do is
	data List_Or t = Item t | List [List_Or t]
			 deriving (Eq, Ord, Show)
and have a "list" like
	ell :: List_Or Int
	ell = List [Item 1, List [Item 2, Item 3], List [Item 4,
	      List [Item 5, Item 6]]]

>> how would i define a function that can iterate through the items so  
>> (in this
>> example)
>> iter1 = 1
>> iter2 = [2,3]
>> iter3 = [4,[5,6]]
>>

Then you can write functions like
	iter n (List x) = head (drop (n-1) x)
with examples
	*Main> iter 1 ell
	Item 1
	*Main> iter 2 ell
	List [Item 2,Item 3]
	*Main> iter 3 ell
	List [Item 4,List [Item 5,Item 6]]

>> ( can i do that without using the Tree data type? )

This basically _is_ a tree data type, even if not THE Tree
data type.  That's because nested lists are trees.

>


More information about the Beginners mailing list