Re: How to get sequence depth

new topic     » goto parent     » topic index » view thread      » older message » newer message
lionel said...

How do you find the depth of a nested sequence? Something like:

depth({}) = 1 
depth({{}}) = 2 
depth({{{}}}) = 3 

and so on. A recursive function, ostensibly. Can anyone write depth() here?

In general, you don't have a single depth in a sequence. It's like an ocean. But you can have the maximum depth. Look at genfunc.e by Ricardo Forno, listed below:

--/topic MISCELLANEOUS ROUTINES 
--/func MaxDepth(object o) 
--/desc Obtains the maximum depth of an object 
--/ret An integer valued as the maximum depth of the argument 
--Returns the maximum depth of object 'o'. 
--Atoms have depth 0. Simple sequences (comprising only atoms) have depth 1. 
-- Sequences comprising only simple sequences and atoms have depth 2. Etc. 
--Examples: MaxDepth(6) gives 0. MaxDepth("Abc") gives 1. 
-- MaxDepth({8,{7,8},6,7}) gives 2. 
global function MaxDepth(object o) 
    integer n, x 
    if atom(o) then 
	return 0 
    else 
	n = 0 
	for i = 1 to length(o) do 
	    x = MaxDepth(o[i]) 
	    if x > n then 
		n = x 
	    end if 
	end for 
	return n + 1 
    end if 
end function 

Regards,
Fernando

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu